Time for me to info dump about Sam and Shelob.
In lord of the rings lore, there are three tiers of deities. The highest tier and most dangerous includes Morgoth - Sauron’s master, and Ungoliant, Shelob’s master. The middle tier includes Shelob, Sauron. Then there’s the lowest tier, which includes the wizards Gandalf and Saruman as well as the Balrog (this is why Gandalf couldn’t 1v1 the Balrog). It also explains why Gandalf doesn’t take the ring, the magic of a tier 2 deity would absolutely corrupt him. We even see that happen with Saruman and the Palantir.
This leads to the start of the answer to some interesting questions. Why does Sauron tolerate Shelob being in his territory, and why does Sauron tolerate there being a secret back door into Mordor?
On the surface, he does it because he might not be able to beat Shelob in a fight, after all they’re the same tier of deity. And since Shelob’s domain is the secret way into Mordor, he can’t close it off, and he seriously doubts anyone can use it to get in. He doesn’t monitor the path with guards either - Shelob would eat them.
It gets more detailed than that though. Sauron’s boss, Morgoth, and Shelob’s boss, Ungoliant, made a deal. They’d attack the tree of life together. Morgoth would drink the nectar, and Ungoliant would keep all of the jewels and magic they earned along the way. Morgoth broke this deal because there was a particularly powerful gem he wanted (the gem in Sauron’s helmet), and as a result Ungoliant went to war with Morgoth.
Ungoliant won, Morgoth barely escaped with his life.
So not only does Sauron maybe lose if he attacks Shelob. Even if he were to win, it might provoke Ungoliant into attacking Morgoth again, and Ungoliant wins that fight, she’s already done it once.
With all of that established, how the hell does Sam hurt a deity that powerful?
Well, to start, it’s impossible. Shelob’s hide is so tough Sam could never pierce it with all his might. However, Shelob had grown old and arrogant. During the fight, Sam winds up directly underneath Shelob, and Shelob decides to crush Sam with all her strength.
Unfortunately, Sam is pointing sting straight up.
While Sam lacks the strength to hurt Shelob, Shelob herself is plenty strong. She accidentally impales herself on sting, finding herself injured for the first time in thousands of years. Which is the sort of poetry I really appreciate about Tolkien’s writing.
No matter how powerful or evil or ancient or indestructible your foe, if you stand for what is right and hold your sword out, they will impale themselves upon it.
Sam’s backstory in this scene is much simpler. He has to save Frodo.