Kakashi didn’t stay dead after Pain’s attack because Naruto later reversed the destruction of the village, which also brought Kakashi back. In other words, he was revived as a result of Pain’s final actions being undone.

What happened

Pain killed Kakashi during the assault on Konoha, but after Naruto defeated Pain, the situation was reversed and Kakashi returned to life.

Why people get confused

A lot of fans remember Kakashi “dying” because the scene is treated like a major death moment, but it was not a permanent death.

Simple version

  1. Pain attacks Konoha.
  2. Kakashi dies in the fight.
  3. Naruto defeats Pain.
  4. The destruction is reversed, and Kakashi comes back.

TL;DR: Kakashi came back because Pain’s devastation was undone after Naruto beat Pain, so his death was not final.