Cain murdered his brother. God punished him in Gen 4:
Onan didn't know it, but the Messiah was supposed to come from Judah, his father. For refusing to cooperate in this matter, God killed him. God is sovereign. He did what he saw fit to do.
On the other hand, Onan practiced coitus interruptus. God punished him in Genesis 38:12 "When you work the ground, it will no longer yield its crops for you. You will be a restless wanderer on the earth.”
Why did God spare Cain but execute Onan?10 What he did was wicked in the Lord’s sight; so the Lord put him to death.
Onan didn't know it, but the Messiah was supposed to come from Judah, his father. For refusing to cooperate in this matter, God killed him. God is sovereign. He did what he saw fit to do.