# How to use pn.state.on\_session\_destroyed

**URL:** <https://discourse.holoviz.org/t/how-to-use-pn-state-on-session-destroyed/5121>\
**Category:** Panel\
**Tags:** panel\
**Created:** [March 21, 2023, 11:10pm UTC](https://discourse.holoviz.org/t/how-to-use-pn-state-on-session-destroyed/5121 "2023-03-21T23:10:51Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![Material-Scientist](https://discourse.holoviz.org/user_avatar/discourse.holoviz.org/material-scientist/32/503_2.png) [@Material-Scientist](https://discourse.holoviz.org/u/Material-Scientist)\
**Post date:** [March 27, 2023, 1:19am UTC](https://discourse.holoviz.org/t/how-to-use-pn-state-on-session-destroyed/5121/10 "2023-03-27T01:19:31Z")

</div>

It happens as sessions are being unloaded from memory. I’ve encountered the same bug numerous times:

[[BUG] background thread stops when session is destroyed, leading to weird errors - Panel - HoloViz Discourse](https://discourse.holoviz.org/t/bug-background-thread-stops-when-session-is-destroyed-leading-to-weird-errors/2962/4)

`'Exception' is not defined` - lol

 ![image](https://discourse.holoviz.org/uploads/default/original/2X/b/b7824c5219b1fcce99ab4c393c7d460b3b3c3b24.jpeg)

`pn.state.on_session_destroyed` callback also doesn’t work when you use lifecycle hooks in a separate file (even though it’s in the state’s callbacks). However, the `on_session_destroyed` callback does get called from within the app\_hooks.py file 🤷‍♂️

Extra FYI:  
The session unloading seems to happen more aggressively when using `--num-threads`  
This is actually a nice bug (feature? 😁 ) as you can get around memory leaks. Even better if you periodically restart your cluster workers to release memory back to the OS:  
 ![image](https://discourse.holoviz.org/uploads/default/original/2X/4/471b0249058c11d79e672ff324f8fe95c314db23.png)

Haven’t had issues with memory leaks since.

Ah, btw - this also makes watcher callbacks fail. Can only let them fail silently as sessions are being unloaded.

![image](https://discourse.holoviz.org/uploads/default/original/2X/a/a0de7dbfb1f45d1457ca66b06ad712a83ec95e53.png)

---

_[View the full topic](https://discourse.holoviz.org/t/how-to-use-pn-state-on-session-destroyed/5121)._
