David’s experience as King of Israel, for him was hard, even though he had fought Lions and Goliath successfully.
His Kingship led him into many areas of life and living which were very painful and which he failed in badly!
Think of Absalom and Bathsheba; both of these were very hurtful experiences, and David failed to do the right thing in each case, and Bathsheba’s was one that led him to plot murder; (apparently without realizing it?)!
These and many other failures in his life, led him many times to points of despair!
Despite his grievous sins, Scripture records that God regards him as “after my own heart” (1Sam.13:14; Acts13:22)!
Psm. 23 is recorded in Scripture by the Holy Spirit, for all those people who would follow King David, Jew and Gentile, who by their free-will want to find the Truth of Jesus!
Jesus said, “I Am The Way, The Truth, and The Life”. David also knew that Truth, and in his sincerity knew that all his mistakes, unconscious sins, and conscious sins could be cleansed and forgiven by God the Father when he was utterly sincere in his regret and sorrow!
David’s faith in God the Father; the “I Am” who spoke to Moses; puts him in the category of the “men of Faith”, described in Hebrews 11!
Hence the great Psm. 23, of David's anguish and joy at his forgiveness!
It is also known as “Messiah’s Psm., as it follows 22; where the crucified Lord is in anguish for the sins of all the world’s people!