<?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 Parahat Iljanov on Medium]]></title>
        <description><![CDATA[Stories by Parahat Iljanov on Medium]]></description>
        <link>https://medium.com/@parahatiljanov?source=rss-f79e7c6240bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yh-GZzPzU7os-GuJOE9hbg.jpeg</url>
            <title>Stories by Parahat Iljanov on Medium</title>
            <link>https://medium.com/@parahatiljanov?source=rss-f79e7c6240bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:36:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parahatiljanov/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[Dynamic Multi-Tenant Architecture with Sequelize and AWS RDS]]></title>
            <link>https://medium.com/@parahatiljanov/dynamic-multi-tenant-architecture-with-sequelize-and-aws-rds-0f3c2ebc2875?source=rss-f79e7c6240bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3c2ebc2875</guid>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[architecture-design]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Parahat Iljanov]]></dc:creator>
            <pubDate>Sun, 18 May 2025 03:32:46 GMT</pubDate>
            <atom:updated>2025-05-18T03:45:29.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaC_gjll4sjOY0cPLTfKUQ.png" /><figcaption>Dynamic Multi-Tenant Architecture with Sequelize and AWS RDS</figcaption></figure><h3>Introduction</h3><p>When building scalable software platforms, one of the architectural challenges is supporting multiple isolated tenants — each with their own database — while maintaining clean code, connection efficiency, and operational control. In this post, I’ll share a practical, production-tested solution for managing <strong>dynamic RDS connections</strong> with Sequelize, using Node.js and AWS.</p><h3>Why Use Separate Databases per Tenant?</h3><p>When working with multiple databases (tenants), common patterns include:</p><ul><li><strong>Shared DB, Shared Schema</strong></li><li><strong>Shared DB, Isolated Schema</strong></li><li><strong>Isolated DB per Tenant </strong>✅</li></ul><p>Using separate databases allows for:</p><ul><li>Complete data isolation</li><li>Individual backups/restores</li><li>Tenant-level performance monitoring</li><li>Easier per-tenant scaling and lifecycle management</li></ul><p>This approach comes with challenges — such as managing connections dynamically, syncing models per database, and preventing boilerplate. Let’s solve that.</p><h3>Core Challenges</h3><ol><li>Dynamically connecting to different databases depending on tenant</li><li>Avoiding duplication across Sequelize model files</li><li>Efficiently managing connections and memory usage</li><li>Ensuring tenant context is preserved throughout requests</li><li>Debugging issues when tenant context is missing or misconfigured</li></ol><h3>Solution Architecture</h3><h4><strong>1. Middleware to Detect Tenant from Request:</strong></h4><p>We’ll rely on the X-Tenant-D header:</p><pre>// tenant-context.ts<br>import { AsyncLocalStorage } from ‘async_hooks’;<br>export const als = new AsyncLocalStorage();</pre><pre>// middleware/tenantMiddleware.ts<br>import { als } from &#39;./tenant-context&#39;;<br><br>export const tenantMiddleware = (req, res, next) =&gt; {<br>  const tenantId = req.get(&#39;X-Tenant-ID&#39;);<br>  if (!tenantId) return res.status(400).send(&#39;Missing X-Tenant-ID&#39;);<br>  als.run(tenantId, () =&gt; next());<br>};</pre><h4><strong>2. Accessing Tenant-Aware Models with a Proxy</strong></h4><p>Instead of manually importing the correct Sequelize instance, use a dynamic proxy:</p><pre>import { als } from &#39;./tenant-context&#39;;<br>import { getModels } from &#39;./db/getModels&#39;;<br><br>const db = new Proxy({}, {<br>  get(_, modelName) {<br>    const tenantId = als.getStore();<br>    if (!tenantId) throw new Error(&#39;No tenant context&#39;);<br>    const models = getModels(tenantId);<br>    if (!models[modelName]) {<br>      throw new Error(`Model &quot;${modelName}&quot; not found for tenant &quot;${tenantId}&quot;`);<br>    }<br>    return models[modelName];<br>  }<br>});</pre><p>Usage:</p><pre>await db.User.findAll();<br>await db.Invoice.create({ amount: 120 });</pre><h4>3. Managing Multiple Sequelize Configurations</h4><p>You can store different configurations per tenant in a single config file:</p><pre>// config/database.config.js<br>module.exports = {<br>  tenantA: {<br>    username: &#39;admin&#39;,<br>    password: &#39;secret&#39;,<br>    database: &#39;tenantA_db&#39;,<br>    host: &#39;tenantA.rds.amazonaws.com&#39;,<br>    dialect: &#39;mysql&#39;,<br>    logging: false,<br>  },<br>  tenantB: {<br>    username: &#39;admin&#39;,<br>    password: &#39;secret&#39;,<br>    database: &#39;tenantB_db&#39;,<br>    host: &#39;tenantB.rds.amazonaws.com&#39;,<br>    dialect: &#39;mysql&#39;,<br>    logging: false,<br>  },<br>  // Add more tenants...<br>};</pre><h4>4. Dynamic Initialization of Models</h4><pre>// db/getModels.ts<br>const { Sequelize } = require(&#39;sequelize&#39;);<br>const configs = require(&#39;../config/database.config&#39;);<br><br>const connectionPool = {};<br><br>function initModels(sequelize) {<br>  const models = {<br>    User: require(&#39;../models/User&#39;)(sequelize),<br>    Invoice: require(&#39;../models/Invoice&#39;)(sequelize),<br>    // Add all models here<br>  };<br><br>  // Associate if needed<br>  Object.values(models).forEach(model =&gt; {<br>    if (typeof model.associate === &#39;function&#39;) model.associate(models);<br>  });<br><br>  return { ...models, sequelize };<br>}<br><br>function getModels(tenantId) {<br>  if (!connectionPool[tenantId]) {<br>    if (!configs[tenantId]) throw new Error(`No DB config for tenant: ${tenantId}`);<br>    const sequelize = new Sequelize(configs[tenantId]);<br>    connectionPool[tenantId] = initModels(sequelize);<br>  }<br>  return connectionPool[tenantId];<br>}<br><br>module.exports = { getModels };</pre><p>This ensures:</p><ul><li>Sequelize is only initialized once per tenant</li><li>Models are synced per database</li><li>You don’t need to rewrite your model logic for each tenant</li></ul><h4>5. Sample Sequelize Model</h4><pre>// models/User.js<br>module.exports = (sequelize) =&gt; {<br>  const { DataTypes } = require(&#39;sequelize&#39;);<br><br>  const User = sequelize.define(&#39;User&#39;, {<br>    id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 },<br>    email: { type: DataTypes.STRING, unique: true, allowNull: false },<br>    name: { type: DataTypes.STRING },<br>  });<br><br>  return User;<br>};</pre><p>You can use the same model definition across all tenants — no duplication needed.</p><h4>6. Initializing Your App with Sequelize Programmatically</h4><p>If you’re not using Sequelize CLI and prefer to initialize tables dynamically, you can sync all tenant databases when the server starts:</p><pre>// At the bottom of app.ts or server.js<br>const { getModels } = require(&#39;./db/getModels&#39;);<br>const configs = require(&#39;./config/database.config&#39;);<br><br>async function initTenants() {<br>  await Promise.all(<br>    Object.keys(configs).map(async (tenantId) =&gt; {<br>      console.log(&quot;🚀 ~ Syncing models for tenant:&quot;, tenantId);<br>      const models = getModels(tenantId); // &lt;-- No Proxy trap used<br>      await models.sequelize.sync(); // Creates tables if they don&#39;t exist<br>    })<br>  );<br>}<br><br>initTenants()<br>  .then(() =&gt; app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`)))<br>  .catch(console.error);</pre><h4>7. Then run per-tenant migration:</h4><pre>npx sequelize-cli db:migrate --env tenantA<br>npx sequelize-cli db:migrate --env tenantB</pre><h3>Common Pitfalls and Debugging Tips</h3><h4>❗ X-Tenant-ID is Missing</h4><p>Ensure you’re passing headers correctly:</p><pre>curl -H &quot;X-Tenant-ID: tenantA&quot; http://localhost:3000/users</pre><p>With Axios (JavaScript example):</p><pre>axios.defaults.headers.common[&#39;X-Tenant-ID&#39;] = process.env.REACT_APP_TENANT_ID;</pre><h4>❗ tenantId is undefined</h4><ul><li>Likely the request isn’t wrapped in als.run(…)</li><li>Ensure middleware is placed before any route handlers or DB usage</li></ul><h3>Best Practices for Production</h3><ul><li>🔄 Use Connection Pooling Efficiently</li><li>🧪 Validate DB Connectivity on Startup</li><li>🔐 Secure Tenant DB Credentials</li><li>📊 Set Up Per-Tenant Health Monitoring</li><li>⚖️ Use Read/Write Replicas for High Throughput</li></ul><h3>Conclusion</h3><p>Supporting multiple databases in a dynamic software project doesn’t have to be complex or messy. By combining AsyncLocalStorage, Sequelize, and clean abstractions like dynamic model proxies, you can isolate tenant data cleanly while maintaining developer productivity and system performance.</p><p>This architecture is scalable, easy to maintain, and suitable for real-world applications that need strict tenant separation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3c2ebc2875" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>