When Tzalya brought Balaam down, Pinchas told him that because of the evil he did on the holy nation, he should die. When Balaam realized that he can’t curse the children of Israel, he expressed his wish to end up with their holiness.
“מִי מָנָה עֲפַר יַעֲקֹב וּמִסְפָּר אֶת רֹבַע יִשְׂרָאֵל תָּמֹת נַפְשִׁי מוֹת יְשָׁרִים וּתְהִי אַחֲרִיתִי כָּמֹהוּ.”
“Who can count the dust of Jacob or number even a fourth of Israel? Let me die the death of the righteous; let my end be like theirs!”
Pinchas told Tzalya to kill Balaam but without using a holy name, so Balaam’s soul won’t depart his body with a connection to holiness.
Tzalya tried several ways to kill Balaam but he couldn’t until he took a sword with a shape of a snake engraved on both sides of the sword. Pinchas said to kill him with his own power that comes from the Snake. So, Balaam was killed by the sword that was supported by the force of death from the Snake.
Balaam wasn’t buried, and all his bones decayed and turned into snakes that harm people. Even the worms that consumed his flesh turned into snakes.
The moment of death is very critical for the departed soul. It’s a difficult process and the body should be buried as soon as possible. According to the laws of Torah, burial should be done on the same day and if possible before sundown because otherwise, the negative forces in this world come immediately to ‘attack’ the body that loses its protection and suck the leftover light left behind after the soul leaves the body.
The first step after the body is buried is called “חיבוט הקבר”, “thrashing in the grave”. It’s an important part that helps the soul disconnect its attachment to the body. It’s a very painful process because the angel of death pushes the soul back into the body and the person feels as if he’s alive in his grave. He is then beaten with iron chains until he is broken to pieces, and he dies again. The process is repeated until the soul is completely detached from the body and ready for the upper court. The level of pain of this process depends on the person’s merits.
Righteous people don’t follow the desires of their body and they may avoid this process unless they missed on something. Those who passed away on Friday afternoon skip this process because of the holiness of Shabbat.
The process of decay is also part of the soul’s cleansing process. On the heavenly court, the actions of the soul are broken down and every little detail is judged.
The more we ‘load’ our souls with Torah studies, the less pain we experience during death. the court process above is easier, including the cleansing time in Gehennam (hell).
Zohar Vayechi has a lot of articles related to the process of the soul after death.