<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Baraka Mwakisha on Medium]]></title>
        <description><![CDATA[Stories by Baraka Mwakisha on Medium]]></description>
        <link>https://medium.com/@barakamwakisha?source=rss-5af3731c63b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gHnXj9KvdYkrwn39PmN9sQ.png</url>
            <title>Stories by Baraka Mwakisha on Medium</title>
            <link>https://medium.com/@barakamwakisha?source=rss-5af3731c63b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:21:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barakamwakisha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Performant Multi-Tenant SaaS Apps with NestJS Durable Providers and Prisma]]></title>
            <link>https://medium.com/@barakamwakisha/performant-multi-tenant-saas-apps-with-nestjs-durable-providers-and-prisma-dc8085310d5a?source=rss-5af3731c63b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc8085310d5a</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[perfomance]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Baraka Mwakisha]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 14:32:19 GMT</pubDate>
            <atom:updated>2023-08-29T07:28:25.999Z</atom:updated>
            <content:encoded><![CDATA[<p>To deliver scalable, cost-effective, and secure services, multi-tenant apps have emerged as the go-to choice for modern SaaS businesses. Imagine a skyscraper housing numerous tenants, each residing independently, yet efficiently sharing resources. Similarly, multi-tenant apps enable a seamless coexistence of multiple users within a single software instance, promoting a sense of personalised experience while optimising resource utilisation.</p><p>Multi-tenancy as a subject is very wide and its various implementation approaches have been covered extensively. This article will focus on schema-based multi-tenancy with Prisma and PostgreSQL.</p><h4>Implementing schema-based multi-tenancy</h4><p>Each tenant’s data is stored in a dedicated database schema in <a href="https://hackernoon.com/your-guide-to-schema-based-multi-tenant-systems-and-postgresql-implementation-gm433589">schema-based multi-tenancy</a>. This segregation ensures that each tenant’s data is isolated from others, preventing any unauthorised access or data leaks. It also provides an efficient way to manage tenants and their data individually.</p><p>In our NestJS API, we need to identify the tenant for each incoming request and provide a Prisma client connected to the tenant’s database schema. But how do we identify tenants? There are several approaches to this. We could assign a separate subdomain per tenant (<em>t001.mysaas.io)</em> or append a tenant-identifying header to each request <em>(x-tenant-id: t001).</em></p><p>Let’s create a <a href="https://docs.nestjs.com/providers">provider</a> to manage Prisma clients.</p><pre>import { Request } from &#39;express&#39;;<br>import { PrismaClient } from &#39;@prisma/client&#39;;<br>import { Injectable, OnModuleDestroy } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class PrismaClientManager implements OnModuleDestroy {<br>  private clients: { [key: string]: PrismaClient } = {};<br><br>  async getClient(request: Request): Promise&lt;PrismaClient&gt; {<br><br>    /* Extract the tenant identifier from the <br>       request object into the tenantId variable */<br><br>    let client = this.clients[tenantId];<br>    if (!client) {<br>      const databaseUrl = process.env.DATABASE_URL.replace(&#39;public&#39;, tenantId);<br><br>      client = new PrismaClient({<br>        datasources: {<br>          db: {<br>            url: databaseUrl,<br>          },<br>        },<br>      });<br><br>      this.clients[tenantId] = client;<br>    }<br><br>    return client;<br>  }<br><br>  async onModuleDestroy() {<br>    await Promise.all(<br>      Object.values(this.clients).map((client) =&gt; client.$disconnect())<br>    );<br>  }<br>}</pre><p>The code above assumes that each database schema is named after the respective tenant identifier and the DATABASE_URL environment variable configured as shown below.</p><pre>DATABASE_URL=&quot;postgresql://postgres:postgres@MY_DB_HOST:5432/MY_SAAS_DB?schema=public&quot;</pre><p>Given the request object, the provider extracts the tenant identifier and replaces the schema in the database URL with it. The provider then constructs a Prisma client for the tenant. For efficiency, an in-memory cache of all constructed Prisma clients is maintained.</p><p>Now let’s create a <a href="https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory">factory provider</a> that will provide injectable Prisma client instances from the Prisma client manager.</p><pre>export const prismaClientProvider: FactoryProvider&lt;PrismaClient&gt; = {<br>  provide: PrismaClient,<br>  scope: Scope.REQUEST,<br>  useFactory: (request: Request, manager: PrismaClientManager) =&gt; {<br>    return manager.getClient(request);<br>  },<br>  inject: [REQUEST, PrismaClientManager],<br>};</pre><p>Notice that this provider is request scoped. This is a significant performance bottleneck. To better appreciate this, we need to understand <a href="https://docs.nestjs.com/fundamentals/injection-scopes#injection-scopes">injection scopes</a> and <a href="https://docs.nestjs.com/fundamentals/injection-scopes#scope-hierarchy">scope hierarchy</a>.</p><h4>Request scope bubbling</h4><p>By default, a single instance of a Nest provider is shared across the entire application. The instance lifetime is tied directly to the application lifecycle. However, for a request-scoped provider, a new instance of the provider is created exclusively for each incoming request. The instance is garbage-collected after the request has completed processing.</p><figure><img alt="Dependency Graph Illustrating Request Scope Bubbling" src="https://cdn-images-1.medium.com/max/1024/1*4WnMVP3SvraGMztOxrJzMQ.png" /><figcaption>Dependency Graph Illustrating Request Scope Bubbling</figcaption></figure><p>Consider the dependency graph above. By default, the users repository, service and controller are singleton-scoped. However, the users service depends on the Prisma client provider which is request-scoped making itself request-scoped. Like a bad case of flu, the request scope bubbles down the graph from the users service to the users controller which also becomes request scoped.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FuUdFariubAfUzWMtCI%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2FDefyTVNetwork-duck-dynasty-defytv-uUdFariubAfUzWMtCI&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2FuUdFariubAfUzWMtCI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/801068fc57525a74e65fc64790dc9288/href">https://medium.com/media/801068fc57525a74e65fc64790dc9288/href</a></iframe><p>The users repository which isn’t dependent on any request-scoped provider remains singleton-scoped.</p><p>The construction and garbage collection of ephemeral request-scoped providers for each request impacts application performance greatly and results in a slower average response time.</p><h4>Durable providers to the rescue</h4><p>Nest v9 introduced <a href="https://docs.nestjs.com/fundamentals/injection-scopes#durable-providers">durable providers</a> that we could use to fix this issue. Instead of recreating the Dependency Injection (DI) tree for each request due to request-scope bubbling, durable providers allow us to create separate DI sub-trees for each tenant aggregated by common request properties, the tenant identifier in our case.</p><figure><img alt="Aggregated DI sub-trees using durable providers" src="https://cdn-images-1.medium.com/max/1024/1*hsHwn47ocN4r8k90NB6z1Q.png" /><figcaption>Aggregated DI sub-trees using durable providers</figcaption></figure><p>Let’s refactor our providers to make them durable. First, we create the aggregation strategy.</p><pre>import {<br>  ContextId,<br>  ContextIdFactory,<br>  ContextIdStrategy,<br>  HostComponentInfo,<br>} from &#39;@nestjs/core&#39;;<br>import { Request } from &#39;express&#39;;<br><br>const tenants = new Map&lt;string, ContextId&gt;();<br><br>export class AggregateByTenantContextIdStrategy implements ContextIdStrategy {<br>  attach(contextId: ContextId, request: Request) {<br><br>    /* Extract the tenant identifier from the <br>       request object into the tenantId variable */<br><br>    let tenantSubTreeId: ContextId;<br>    if (tenants.has(tenantId)) {<br>      tenantSubTreeId = tenants.get(tenantId);<br>    } else {<br>      tenantSubTreeId = ContextIdFactory.create();<br>      tenants.set(tenantId, tenantSubTreeId);<br>    }<br><br>    return {<br>      resolve: (info: HostComponentInfo) =&gt;<br>        info.isTreeDurable ? tenantSubTreeId : contextId,<br>      payload: { tenantId },<br>    };<br>  }<br>}</pre><p>Now let’s register the strategy in the bootstrap function of the <strong>main.ts</strong> file.</p><pre>ContextIdFactory.apply(new AggregateByTenantContextIdStrategy());<br></pre><p>Next, let’s refactor the Prisma client provider and manager.</p><pre>export interface ContextPayload {<br>  tenantId: string;<br>}<br><br>export const prismaClientProvider: FactoryProvider&lt;PrismaClient&gt; = {<br>  provide: PrismaClient,<br>  scope: Scope.REQUEST,<br>  durable: true, // Makes this provider durable<br>  useFactory: (ctxPayload: ContextPayload, manager: PrismaClientManager) =&gt; {<br>    /* <br>      The tenantId in the context payload registered <br>      in the AggregateByTenantContextIdStrategy <br>    */<br>    return manager.getClient(ctxPayload.tenantId);<br>  },<br>  inject: [REQUEST, PrismaClientManager],<br>};</pre><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br>import { Injectable, OnModuleDestroy } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class PrismaClientManager implements OnModuleDestroy {<br>  private clients: { [key: string]: PrismaClient } = {};<br>  <br>  // Now takes the tenantId from prismaClientProvider as an argument<br>  async getClient(tenantId: string): Promise&lt;PrismaClient&gt; {<br>    let client = this.clients[tenantId];<br>    if (!client) {<br>      const databaseUrl = process.env.DATABASE_URL.replace(&#39;public&#39;, tenantId);<br><br>      client = new PrismaClient({<br>        datasources: {<br>          db: {<br>            url: databaseUrl,<br>          },<br>        },<br>      });<br><br>      this.clients[tenantId] = client;<br>    }<br><br>    return client;<br>  }<br><br>  async onModuleDestroy() {<br>    await Promise.all(<br>      Object.values(this.clients).map((client) =&gt; client.$disconnect())<br>    );<br>  }<br>}</pre><p>Voila! With any luck, you should now be experiencing much faster response times thanks to the per-tenant durable DI sub-trees.</p><h4>In conclusion</h4><p>While this approach results in better performance, it is worth mentioning that the <a href="https://docs.nestjs.com/fundamentals/injection-scopes#durable-providers">Nest docs</a> state that <strong>this approach is not suitable for applications operating with a large number of tenants.</strong> Extra tooling will also be required to handle Prisma migrations across client schemas. <a href="https://thomasvds.com/schema-based-multitenancy-with-nest-js-type-orm-and-postgres-sql/">This article</a> goes deeper into NestJS multi-tenancy with PostgreSQL and TypeORM and is definitely a worthy read.</p><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc8085310d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>