DEV Community

Krzysztof Platis
Krzysztof Platis

Posted on • Edited on

2

ngOnDestroy in services - unsubscribe to avoid memory leaks in SSR Angular 💧

I believed that I don’t need to unsubscribe RxJs subscriptions created in Angular singleton services, but only in components. I changed my mind when saw memory leaks in SSR (Angular Universal).

One NodeJS process, but many rendered apps

The NodeJS process of the SSR server on every http request: bootstraps a fresh Angular app, sends the output HTML to the client, and destroys the app. This cycle is repeated for each request inside one shared long-living NodeJS process. So any pending subscription created in any app’s service survives even after the app is destroyed. And it causes memory leaks in the server.

Unsubscribe in services’ ngOnDestroy

Angular invokes in SSR the lifecycle method ngOnDestroy not only for components, but also for every service, when the app is destroyed. Therefore it’s a good place to unsubscribe any pending subscriptions created by the service.

If you really feel like buying me a coffee

... then feel free to do it. Many thanks! 🙌

Buy Me A Coffee

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (1)

Collapse
 
theoklitosbam7 profile image
Theoklitos Bampouris •

This is not restricted to SSR. You may check out my article:
dev.to/theoklitosbam7/avoid-memory...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more