In Psalm 25:20, David asked the Lord to guard him and then in v.21, he uses a synonymous verb to say that his integrity and uprightness guards him. Which is it that guards him?—God or his character. Both! We know that God’s power is ultimately the cause of any preservation of our souls, but we can have no confidence to be preserved if we lean on our own understanding and do things our own way.
Truths like this make us uncomfortable sometimes because we have been conditioned so heavily to guard against a works-based salvation and rightly so—no one can possibly get right with God or be justified by their works. But that being said, works are absolutely necessary to persevere in the Christian life, just as James 2 and 2 Pet. 1 make very clear.
In terms of another way to think about how godliness preserves us, consider what the characteristics of v.21 are keeping David from—self-protective dispositions, such as bitterness or vengeance. No one can expect God’s preserving grace while lifting up one’s soul to sinful things like that. Imagine how that sounds to God: “Please bless me God while I remain bitter or continue to coddle vengeful thoughts.”
This corresponds to the end of v.21, which we already mentioned in v.3—David can ask that his integrity and uprightness preserve him because he’s waiting on God, which means he is hoping in God to act according to his word and his character and we can’t have that confident expectation if we have abandoned God’s will. But when we are waiting for him to work according to his promises, he is a shield to our souls so that we may not stumble.