<?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"><channel><title><![CDATA[Usman Hafeez's Blog]]></title><description><![CDATA[Usman Hafeez's Blog]]></description><link>https://usmanhafeez147.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 13:36:14 GMT</lastBuildDate><atom:link href="https://usmanhafeez147.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building Reliable IoT Messaging with NestJS, MQTT and MongoDB]]></title><description><![CDATA[Patterns for reliable device backends: MQTT topic design, device provisioning, QoS choices, idempotent processing and MongoDB transactions in NestJS.]]></description><link>https://usmanhafeez147.hashnode.dev/building-reliable-iot-messaging-with-nestjs-mqtt-and-mongodb</link><guid isPermaLink="true">https://usmanhafeez147.hashnode.dev/building-reliable-iot-messaging-with-nestjs-mqtt-and-mongodb</guid><category><![CDATA[nestjs]]></category><category><![CDATA[mqtt]]></category><category><![CDATA[iot]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Usman Hafeez]]></dc:creator><pubDate>Mon, 23 Nov 2026 11:28:46 GMT</pubDate><content:encoded><![CDATA[<p>Devices in the field do not behave like browsers. They lose power, drop off the network, reconnect with old data, and sometimes send the same message twice. If your backend assumes every message arrives once, in order, on time, it will slowly fill up with wrong data.</p>
<p>I have built backends for connected devices on a few products, including a NestJS and MongoDB platform that talks to devices over MQTT, and Saferide, where we built the APIs and infrastructure for vehicle tracking, including how new devices get provisioned. This post collects the patterns that made those systems reliable. It is less about any one product and more about the decisions that matter whenever you connect real hardware to a backend.</p>
<h2>Why MQTT</h2>
<p>MQTT is a lightweight publish and subscribe protocol built for devices with limited power and unreliable connections. Devices keep one long-lived connection to a broker, publish messages to topics, and subscribe to the topics they care about. The backend does the same. Nobody talks directly to anybody else.</p>
<p>That design fits devices well. A device does not need to know where the backend lives or how many backend instances are running. It only needs to reach the broker. The backend can restart, scale up or move to a new server without devices noticing.</p>
<h2>Topic design is your API design</h2>
<p>With MQTT, the topic structure is effectively your API, and it is hard to change once thousands of devices are in the field. We spent real time on it before shipping anything.</p>
<p>The rule we settled on is that every topic says who the message belongs to and what kind of message it is, from broadest to most specific: the tenant, then the device, then the message type. Device telemetry goes on one kind of topic, status changes on another, and commands from the backend to the device on a separate one.</p>
<p>This structure does two useful things. The backend can subscribe to exactly the traffic it needs using wildcards, such as all telemetry for every device, without parsing everything. And the broker's access rules can be written per topic, so a device can only publish to its own topics and only read its own commands.</p>
<h2>Identity and provisioning</h2>
<p>Every device needs its own identity. Shared credentials across a whole fleet mean one leaked password exposes every device, and you cannot cut off one bad device without cutting off all of them.</p>
<p>On Saferide, provisioning was a proper flow, not a manual step. A new device is registered in the platform first, tied to a tenant and a vehicle, and only then issued its own credentials for the broker. Until a device has been provisioned and assigned, the backend ignores anything it sends. When a device is retired or stolen, revoking its credentials cuts it off on its own without touching the rest of the fleet.</p>
<p>The same registry answers a question you will be asked constantly in support: "Is this device ours, which customer has it, and when did it last talk to us?"</p>
<h2>Choosing delivery guarantees deliberately</h2>
<p>MQTT offers three quality of service levels: at most once, at least once, and exactly once. It is tempting to pick the strongest everywhere. It is usually a mistake.</p>
<p>High-frequency telemetry, like a position every few seconds, works fine with at most once delivery. If one point is lost, the next one arrives shortly after, and the extra overhead of stronger guarantees on every point costs battery and bandwidth.</p>
<p>Important events are different. A status change, an alarm or a completed transaction must not be lost, so those use at least once delivery. And at least once means exactly what it says: sometimes the same message arrives twice. The backend has to be ready for that.</p>
<h2>Making the backend idempotent</h2>
<p>The most important pattern in any device backend is idempotency: processing the same message twice must have the same effect as processing it once.</p>
<p>Every important message carries a unique ID created by the device, plus the device's own timestamp. Before acting on a message, the backend checks whether that ID has already been processed. If it has, the message is acknowledged and ignored. In MongoDB, a unique index on the message ID makes this check reliable even when several backend instances process messages at the same time, because the database itself refuses the duplicate.</p>
<p>Device timestamps matter just as much. Devices that were offline send their buffered messages when they reconnect, often all at once and out of order. If the backend uses the time a message arrived, an old reading can overwrite a newer one. Using the device's timestamp, and refusing to replace a newer state with an older one, keeps the data correct.</p>
<h2>Transactions where money or state is involved</h2>
<p>On the NestJS platform, some device messages trigger changes that must happen together or not at all, such as recording an event and updating a balance or a usage counter. If the process crashes halfway through, you end up with one change applied and the other missing.</p>
<p>For those cases we used MongoDB multi-document transactions, wrapped in a NestJS service so the rest of the code did not have to think about them. The duplicate check, the event record and the related updates all happen inside one transaction. Either everything is written, or nothing is, and the message can be safely retried.</p>
<p>We kept transactions only where they were needed. Plain telemetry does not need them, and using them everywhere would only slow the system down.</p>
<h2>Structuring it in NestJS</h2>
<p>NestJS has built-in support for MQTT as a microservice transport, which lets you handle MQTT messages with the same structure as HTTP controllers. We used that to keep message handling clean.</p>
<p>Each message type has its own handler. Incoming messages are validated against a schema before any business logic runs, so a device with buggy firmware cannot write malformed data into the database. Business logic lives in services that know nothing about MQTT, so the same logic can be triggered by a device message, an HTTP call or a test, which made it far easier to test.</p>
<h2>Watching the fleet</h2>
<p>Finally, a device platform needs to notice silence. A device that stops sending messages does not raise an error, it just goes quiet.</p>
<p>We track the last time each device was heard from and flag devices that have been quiet longer than expected for their type. We also watch for the opposite problem: a device that suddenly sends far more messages than normal is often a firmware bug, and it is better to catch it before it fills your database.</p>
<h2>The short version</h2>
<p>Design topics carefully, because they are your API. Give every device its own identity through a real provisioning flow. Choose delivery guarantees per message type. Assume every important message can arrive twice and out of order, and make processing idempotent. Use transactions only where partial writes would hurt. And watch for devices that go quiet.</p>
<p>None of these ideas are new, but skipping any one of them shows up later as data that is slightly wrong in ways that are very hard to trace.</p>
<hr />
<p><em>I'm Usman Hafeez, a System Architect and Full-Stack Tech Lead. I build multi-tenant SaaS platforms, IoT backends and AI agent features with Node.js, NestJS, AWS and Kubernetes. More of my work is at</em> <a href="https://usmanhafeez147.vercel.app"><em>usmanhafeez147.vercel.app</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Live GPS Tracking for a Multi-Tenant Fleet Platform with Socket.IO and Redis]]></title><description><![CDATA[How one Node.js API streams live bus positions to six apps with Socket.IO and Redis, keeps tenants isolated and handles offline drivers.]]></description><link>https://usmanhafeez147.hashnode.dev/live-gps-tracking-for-a-multi-tenant-fleet-platform-with-socket-io-and-redis</link><guid isPermaLink="true">https://usmanhafeez147.hashnode.dev/live-gps-tracking-for-a-multi-tenant-fleet-platform-with-socket-io-and-redis</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Socket.io]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Real Time]]></category><category><![CDATA[SaaS]]></category><dc:creator><![CDATA[Usman Hafeez]]></dc:creator><pubDate>Mon, 23 Nov 2026 11:26:55 GMT</pubDate><content:encoded><![CDATA[<p>When a parent scans the QR code at a school bus stop, they see the bus moving on a map in real time. Behind that small map is one of the busiest parts of the fleet platform I build for passenger transport operators.</p>
<p>The platform has one Node.js API and six client apps: Next.js admin and customer portals, a native Kotlin driver app, an Expo driver app for iOS and Android, a web driver app, and a public site where parents and passengers follow their bus. Driver apps send GPS positions, and everyone else watches them move.</p>
<p>This post explains how live tracking works across all of those clients: how positions flow in, how they reach exactly the right people, and what we learned keeping it reliable on real roads with real phones.</p>
<h2>One API, many clients</h2>
<p>We made an early decision to keep a single backend: one Express API that serves REST for normal data and Socket.IO for live updates, backed by MongoDB and Redis. Every client, native or web, talks to the same API.</p>
<p>That decision saved us a lot of time. Business rules live in one place. A route change or a permission change applies to every app at once. And live tracking has one source of truth, so the admin map and the parent's map never disagree about where a bus is.</p>
<h2>How positions flow in</h2>
<p>Driver apps send a position update every few seconds while a trip is active, with latitude, longitude, speed, heading and the device's own timestamp. Updates go over the existing Socket.IO connection rather than separate HTTP requests, because opening a new request every few seconds on a weak mobile network wastes battery and data.</p>
<p>The server does very little with each update on the hot path. It checks that the driver is authenticated and is actually assigned to an active trip on that vehicle, drops points that are obviously wrong, stores the latest position in Redis, and broadcasts it. Heavier work, like saving the full route history and calculating delays, runs in the background so it never slows down the live feed.</p>
<p>Throwing away bad points matters more than it sounds. Phone GPS jumps around, especially near tall buildings and in tunnels. A single bad reading can make a bus appear to teleport across the city. We drop points that imply an impossible speed since the last good point, and points with very poor reported accuracy. Parents do not need every point. They need a bus that moves believably.</p>
<h2>Getting each update to the right people only</h2>
<p>This is the part where multi-tenancy really matters. Many operators share the same API, and a parent tracking one school bus must never see the rest of the fleet, let alone another operator's vehicles.</p>
<p>We use Socket.IO rooms. Each vehicle on an active trip has its own room, and each operator has an operator-wide room. When a position comes in, the server sends it to that vehicle's room and that operator's dispatch room, and nowhere else.</p>
<p>Who can join which room is decided on the server, never by the client. An admin's connection is authenticated, and the server puts it in their operator's dispatch room based on their role. A parent's QR code gives them a short-lived, read-only token for one route. The server checks that token and lets them join only the rooms for vehicles running that route. If a parent edits the request to ask for a different vehicle, the server simply refuses.</p>
<p>Public tracking pages also get less data than internal ones. A parent sees the bus position and the estimated arrival time. They do not see the driver's details, the full trip history or other passengers.</p>
<h2>Scaling Socket.IO across servers</h2>
<p>A single Node.js process can hold a lot of connections, but not forever, and we wanted more than one instance for reliability anyway. The problem with running several instances is that a driver might be connected to one server while the parents watching that bus are connected to another.</p>
<p>The Socket.IO Redis adapter solves this. When one instance broadcasts to a room, the adapter passes the message through Redis to every other instance, and each one delivers it to its own connected clients. From the application's point of view, rooms work the same no matter how many servers are running.</p>
<p>We also keep the latest known position of every active vehicle in Redis. When someone opens a map, they get the current positions immediately from Redis instead of waiting a few seconds for the next update to arrive. That small detail makes the map feel live from the first moment.</p>
<h2>Dealing with real-world networks</h2>
<p>Driver phones lose signal all the time: rural roads, underpasses, depots with bad coverage. The tracking system has to treat this as normal, not as an error.</p>
<p>When a driver app goes offline, it keeps recording positions locally and sends the missed points when it reconnects. The server accepts them, uses them to fill in the route history, but does not replay them on the live map, because an old point is not where the bus is now. That is why every update carries the device's own timestamp, not just the time the server received it.</p>
<p>On the watching side, the map shows when a position is stale. If we have not heard from a bus for a while, the marker fades and shows when it was last seen, instead of pretending the bus is parked. Being honest about missing data builds more trust than a map that silently stops moving.</p>
<p>Socket.IO handles reconnection on the client side, and after reconnecting, each client rejoins its rooms through the same server-side checks. Nobody keeps access just because they had it before a dropped connection.</p>
<h2>Keeping costs down</h2>
<p>Live tracking is constant traffic, so small inefficiencies add up. A few habits helped. We only send position updates while a trip is active, not all day. We send only the fields that changed and that the viewer needs. And public viewers get updates at a gentler rate than dispatchers, because a parent does not need a new point every second to know the bus is two stops away.</p>
<h2>What I would keep, and what I would change</h2>
<p>I would keep the single API serving every client, server-side room authorization, Redis for both the latest positions and cross-instance broadcasting, and the habit of filtering bad GPS points before anyone sees them.</p>
<p>What I would do earlier is treat offline drivers and stale positions as a core feature from the first version. We added that after the first weeks in the field, and it changed how much operators trusted the map.</p>
<p>Live tracking looks like a map with a moving dot. Most of the real work is making sure the right people see the right dot, that the dot is believable, and that it keeps working when the network does not.</p>
<hr />
<p><em>I'm Usman Hafeez, a System Architect and Full-Stack Tech Lead. I build multi-tenant SaaS platforms on AWS and Kubernetes, and real-time systems with Node.js, Socket.IO and Redis. More of my work is at <a href="https://usmanhafeez147.vercel.app">usmanhafeez147.vercel.app</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Letting an AI Assistant Query Live Fleet Data Safely with an MCP Server]]></title><description><![CDATA[How a 29-tool MCP server lets an AI assistant query a live multi-tenant fleet platform safely: tenant isolation, role checks, read-only tools.]]></description><link>https://usmanhafeez147.hashnode.dev/letting-an-ai-assistant-query-live-fleet-data-safely-with-an-mcp-server</link><guid isPermaLink="true">https://usmanhafeez147.hashnode.dev/letting-an-ai-assistant-query-live-fleet-data-safely-with-an-mcp-server</guid><category><![CDATA[SaaS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Security]]></category><category><![CDATA[mcp]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Usman Hafeez]]></dc:creator><pubDate>Mon, 23 Nov 2026 11:25:10 GMT</pubDate><content:encoded><![CDATA[<p>I build a multi-tenant platform for passenger transport operators: school buses, charter coaches and shuttle fleets. Operators manage vehicles, drivers, routes and trips, drivers run their shifts from a mobile app, and parents follow the bus live from a QR code.</p>
<p>A few months in, the most common request from operators was not a new screen. It was a question. "Which buses are running late right now?" "Which driver has the most trips this week?" "Is route 12 still on the old schedule?" The answers were all in our system, but getting them meant clicking through three or four pages.</p>
<p>So we added an MCP server. It exposes 29 tools that let an AI assistant read live fleet data and answer those questions in plain language. This post is about how we built it, and mostly about how we kept it safe, because giving an AI model access to production data across many tenants is easy to get wrong.</p>
<h2>What MCP gives you</h2>
<p>The Model Context Protocol is an open standard for connecting AI assistants to outside systems. Instead of writing a custom integration for every assistant, you build one MCP server that describes a set of tools: their names, what they do, and what inputs they take. Any MCP-compatible client can then discover those tools and call them when a user's question needs them.</p>
<p>For us, that meant the fleet platform did not need its own chatbot. An operator can use an assistant they already know, connect it to our server, and ask questions about their own fleet.</p>
<h2>Designing tools around questions, not tables</h2>
<p>Our first instinct was to expose the database: a tool to list vehicles, a tool to list trips, a tool to list drivers. That worked badly. The assistant had to pull large lists and do the filtering itself, which was slow, expensive in tokens, and sometimes wrong.</p>
<p>What worked was designing each tool around a question an operator actually asks. "Get vehicles that are currently off route." "Get today's trips for a driver." "Get late arrivals for a route in a date range." Each tool does the filtering on the server, where the data and the indexes live, and returns a small, focused answer.</p>
<p>That is how we ended up with 29 tools rather than five. Small tools with clear names and descriptions are easier for the model to pick correctly. The tool description is part of the interface. We wrote each one the way you would explain it to a new team member: what it returns, when to use it, and what it does not cover. When the assistant picked the wrong tool, the fix was almost always a better description, not more code.</p>
<p>We also kept the output shape boring and consistent. Every tool returns plain, labeled fields with units in the name: minutes late, distance in kilometers, times with their time zone. Ambiguous output is where models make things up, so we removed as much ambiguity as we could.</p>
<h2>Tenant isolation comes first</h2>
<p>The platform is multi-tenant. Many operators share the same API and the same database. The single most important rule for the MCP server was that an assistant connected for one operator can never see another operator's data, no matter what the user types.</p>
<p>We did not trust the model to enforce that. The model never chooses the tenant. When an assistant connects, it authenticates with a token tied to one user in one tenant. Every tool call runs through the same authorization layer as our normal API, and the tenant is taken from that token on the server, never from the tool's inputs. There is simply no parameter the model could fill in to ask for someone else's fleet.</p>
<p>This matters because prompt injection is real. A trip note, a driver's name or a route description could contain text that tries to steer the assistant. If the security boundary lived in the prompt, one clever string could break it. Because it lives in the server, the worst a manipulated assistant can do is ask for data the user was already allowed to see.</p>
<h2>Respecting roles, not just tenants</h2>
<p>Inside one operator, people have different roles. A dispatcher sees live operations. A finance user sees billing. A driver sees their own trips. The web portals already enforce this through role-based access control, and the MCP server had to follow exactly the same rules.</p>
<p>We reused the existing permission checks instead of writing new ones for the AI path. Every tool declares which permission it needs, and the server checks it before running anything. If a user without access to driver records asks about a driver's hours, the tool returns a clear "not permitted" message. The assistant passes that on instead of guessing.</p>
<p>Reusing the same checks was a deliberate choice. Two separate permission systems drift apart over time, and the AI path would quietly become the weaker one.</p>
<h2>Read-only by default</h2>
<p>Every one of the first set of tools only reads data. Nothing the assistant does can cancel a trip, reassign a driver or change a route.</p>
<p>Write actions are tempting, and some operators asked for them. But a wrong answer from a read tool is an annoyance, while a wrong action on a live fleet can leave children waiting at a bus stop. If we add write tools later, they will need an explicit confirmation step from the human, and they will be limited to small, reversible actions.</p>
<h2>Keeping it fast and cheap</h2>
<p>Assistants often call several tools to answer one question, so slow tools add up quickly. Most of our tools read from data that is already hot. Live vehicle positions sit in Redis, because the tracking system writes them there anyway, so "where is bus 14 right now" never touches the main database. Heavier questions, like weekly trip counts, use indexed queries with date limits that the server enforces even if the assistant asks for more.</p>
<p>We also cap how much any tool can return. If a question would produce hundreds of rows, the tool returns a summary and the top results, and says how many more exist. That keeps responses small for the model and stops a broad question from turning into a heavy database scan.</p>
<h2>Logging every call</h2>
<p>Every tool call is logged with the user, the tenant, the tool name, the inputs and how long it took. This gave us three things.</p>
<p>It gave us security visibility: if anything ever looked wrong, we could see exactly what was asked and what was returned.</p>
<p>It gave us a roadmap: the logs showed which questions people asked most, and which questions the assistant could not answer with the tools it had. Several of the later tools came straight from those gaps.</p>
<p>And it gave us quality data: when an operator said the assistant gave a wrong answer, we could replay the exact tool calls and see whether the data was wrong or the model misread it.</p>
<h2>What I would tell someone starting today</h2>
<p>Design tools around real questions, keep them small, and spend real time on their descriptions. Put tenant and role checks in the server, never in the prompt, and reuse the checks your API already has. Start read-only. Log everything.</p>
<p>Most of the work in a good MCP server is not AI work at all. It is ordinary backend engineering: clear interfaces, strict authorization and fast queries. The model is only as useful, and only as safe, as the tools you give it.</p>
<hr />
<p><em>I'm Usman Hafeez, a System Architect and Full-Stack Tech Lead. I build multi-tenant SaaS platforms on AWS and Kubernetes, and AI agent features with LangChain, LangGraph and MCP. More of my work is at <a href="https://usmanhafeez147.vercel.app">usmanhafeez147.vercel.app</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[How We Serve 100+ Client Websites from One Multi-Tenant SaaS on AWS EKS]]></title><description><![CDATA[How one Next.js renderer on AWS EKS serves 100+ customer websites: routing, automatic HTTPS for custom domains, Redis caching and safe deploys.]]></description><link>https://usmanhafeez147.hashnode.dev/how-we-serve-100-client-websites-from-one-multi-tenant-saas-on-aws-eks</link><guid isPermaLink="true">https://usmanhafeez147.hashnode.dev/how-we-serve-100-client-websites-from-one-multi-tenant-saas-on-aws-eks</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[AWS]]></category><category><![CDATA[SaaS]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[Usman Hafeez]]></dc:creator><pubDate>Mon, 23 Nov 2026 10:52:16 GMT</pubDate><content:encoded><![CDATA[<p>At work we build a no-code website builder. A customer picks a template, edits pages in the builder, and publishes. A few minutes later the site is live on its own subdomain or on the customer's own domain, with HTTPS.</p>
<p>Today the platform serves more than 100 live websites, and launching a new one takes about 70% less time than it did when every site was its own deployment. We did not get there by adding more servers. We got there by deciding early that a website is a row in a database, not a deployment.</p>
<p>This post explains how that works: how a request for any customer domain finds the right site, how certificates get issued without anyone touching them, how we cache tenant data, and how we deploy without breaking 100 sites at once. Our stack is Next.js, Redis, cert-manager and Helm on Amazon EKS, but the ideas carry over to other stacks.</p>
<h2>The core idea: one renderer, many hostnames</h2>
<p>The naive way to host many client sites is one container (or one Vercel project, or one VM) per site. It feels simple at first. Then you have 40 sites, and a security patch means 40 builds and 40 deploys. Every site has its own config drift. Your cloud bill grows in a straight line with your customer count.</p>
<p>We went the other way. There is one service, the site renderer, and it serves every customer site. When a request comes in, the renderer looks at the hostname the visitor asked for, finds which site owns that hostname, loads that site's pages and theme, and renders them.</p>
<p>So the whole platform has three moving parts on the request path:</p>
<ol>
<li>An ingress layer that accepts traffic for any hostname and handles HTTPS.</li>
<li>The renderer, a Next.js app that works out which customer a request belongs to.</li>
<li>A tenant store, the database where sites, pages and domains live, with Redis in front of it.</li>
</ol>
<p>Adding a customer adds data, not infrastructure. That is the whole trick, and the rest of this post is the detail that makes it hold up in production.</p>
<h2>Routing every hostname to one service</h2>
<p>Every customer gets a free subdomain like <a href="http://acme.sites.example.com">acme.sites.example.com</a>. For those, we only need one wildcard routing rule in Kubernetes. It says that any hostname ending in our sites domain goes to the renderer service, and it uses a single wildcard certificate that covers all of them.</p>
<p>That one rule means every subdomain we will ever create already works. Creating a new site does not touch Kubernetes at all. It is a database insert and nothing else.</p>
<p>A wildcard certificate needs the DNS challenge, because Let's Encrypt has to confirm that you control the whole domain, not just one hostname. On AWS that means cert-manager updates Route 53 to prove ownership. We give cert-manager its own narrow IAM role through IRSA (IAM roles for service accounts), so there are no AWS access keys stored anywhere in the cluster. The certificate renews itself before it expires, and nobody on the team has had to think about it since.</p>
<h2>Custom domains and automatic HTTPS</h2>
<p>Subdomains are easy. Custom domains are where most multi-tenant platforms get painful, because you cannot get a wildcard certificate for domains you do not own.</p>
<p>Our flow works like this. The customer adds <a href="http://www.acme.com">www.acme.com</a> in the builder, and we show them one DNS record to create, a CNAME pointing to our platform. In the background, our backend keeps checking that domain. As soon as the DNS record points to us, the backend creates a small routing rule just for that domain through the Kubernetes API. cert-manager sees the new rule, completes a Let's Encrypt HTTP challenge for that single domain, and stores the certificate. A few minutes later the customer's site is live on their domain with HTTPS. They never upload a certificate or open a support ticket.</p>
<p>Two rules saved us real trouble here.</p>
<p>First, never create the routing rule before DNS points to you. If you do, the certificate challenge fails, cert-manager retries with growing delays, and if it happens across many domains you start hitting Let's Encrypt rate limits. We confirm DNS first and only then ask for a certificate.</p>
<p>Second, the backend's Kubernetes permissions are as narrow as we could make them. It can create and delete routing rules in the one namespace where customer sites live, and nothing else. This service is talking to the cluster API, so if it is ever compromised, the damage it can do should be small.</p>
<p>When a customer removes a domain, the same job deletes the routing rule and its certificate, so the cluster does not slowly fill up with dead certificates for domains we no longer serve.</p>
<h2>Working out the tenant inside Next.js</h2>
<p>Once a request reaches the renderer, the app has to turn a hostname into a site. In the Next.js App Router we split this into two small steps.</p>
<p>Next.js middleware runs first on every request. Ours does one thing only: it reads the hostname and quietly rewrites the request to an internal route that includes that hostname. The visitor still sees <a href="http://www.acme.com/about">www.acme.com/about</a> in the browser. Internally, Next.js serves a route like /sites/<a href="http://www.acme.com/about">www.acme.com/about</a>, so the page code receives the hostname as a normal route parameter, the same way it would receive a product ID.</p>
<p>The page then looks up the site for that hostname, finds the page that matches the path, and renders it with that customer's theme. If there is no site for the hostname, or no page for the path, it returns a normal 404.</p>
<p>We keep the middleware dumb on purpose. It never calls the database. That keeps it fast, and it means a slow database cannot block every single request at the front door. All tenant logic lives in normal server code, where we have proper error handling, timeouts and logging.</p>
<h2>Caching tenants so the database does not take every hit</h2>
<p>Every page view needs the site config: theme, navigation, pages and settings. Reading that from the database on every request works at 10 sites. At 100 sites with real traffic, it is the first thing that falls over.</p>
<p>So every lookup goes through Redis first. The key is the hostname, and the value is that site's config. If Redis has it, the database is never touched. If not, we read from the database once and store the result in Redis for five minutes.</p>
<p>The detail most people forget is caching the misses. Bots scan every public IP address all day, sending made-up hostnames. Without care, each one of those becomes a database query that finds nothing. We store "no site for this hostname" in Redis too, for a shorter time, so junk traffic stops at the cache.</p>
<p>The other half is invalidation. When a customer clicks Publish, the builder saves the new version and then immediately deletes the cache entries for every hostname that site owns, both its subdomain and any custom domains. The next visitor gets fresh content. We do not wait for the five-minute expiry, because "I published and nothing changed" would quickly become our most common support ticket.</p>
<h2>Isolating tenants that share a process</h2>
<p>Sharing one renderer between all customers is what makes the platform cheap. It is also what makes it risky, because one bug or one heavy site can affect everyone. We handle that in three places.</p>
<p><strong>Data.</strong> Every query that touches site data goes through a function that requires a site ID. The renderer has no "list all pages" query at all. The only way to reach any data is through a specific tenant, so one customer's page cannot leak into another customer's site because someone forgot a filter.</p>
<p><strong>Load.</strong> Pages are rendered on the server and the HTML is cached, so a traffic spike on one site mostly hits the cache, not the CPU. On top of that, Kubernetes scales the renderer automatically on CPU usage, between a minimum of three copies and a maximum of twenty. The three-copy minimum is spread across different availability zones, so losing a server, or even a whole AWS zone, does not take any site offline.</p>
<p><strong>Visibility.</strong> Every log line and every metric carries the hostname. When something goes wrong, the first question is always "is it one site or all of them?" With the hostname everywhere, we can answer that in seconds instead of guessing.</p>
<h2>Deploying without breaking 100 sites at once</h2>
<p>When every customer runs on the same service, a bad deploy is not one broken site. It is all of them. Since we moved releases to the setup below, production incidents dropped by about 75%, and most of that came from making deploys boring and reversible.</p>
<p>Releases run through GitHub Actions. On every merge to the main branch, the pipeline logs in to AWS using short-lived OIDC credentials, so there are no long-lived AWS keys saved in GitHub. It builds a Docker image, pushes it to Amazon ECR, and rolls it out to EKS with Helm.</p>
<p>Three details in that pipeline matter more than they look.</p>
<p><strong>Every image is tagged with its Git commit.</strong> We never deploy an image called "latest". Any running copy of the app can be traced back to the exact commit that produced it, and rolling back simply means deploying an older commit.</p>
<p><strong>Failed releases roll themselves back.</strong> Helm waits for the new version to become healthy within five minutes. If it does not, Helm restores the previous version automatically and the pipeline fails. A broken release breaks the build, not the websites.</p>
<p><strong>Health checks test something real.</strong> A container being "up" means very little. Our readiness check renders a real test site from start to finish, which touches the database and Redis. A new copy of the app that starts but cannot reach Redis never receives customer traffic.</p>
<p>Before a release reaches production, it also renders a set of real customer templates in staging. Templates are where regressions hide, because a small CSS or component change that looks fine on one template can break the layout of another.</p>
<h2>Keeping the bill flat as customers grow</h2>
<p>Because a new site is a database row, cost follows traffic, not customer count. That is the main reason our cloud spend came down by 20 to 40% compared with running sites one by one. The rest came from a few simple habits.</p>
<p>The renderer stores nothing on its own disk, so it runs well on cheaper Spot instances. If AWS takes one back, Kubernetes simply starts the app elsewhere. Stateful parts, like Redis and the databases, stay on regular on-demand capacity or managed services.</p>
<p>We set each service's CPU and memory requests from real usage graphs, not guesses. Oversized requests are the most common reason an EKS cluster costs more than it should, because Kubernetes reserves capacity that is never used.</p>
<p>Images, scripts and styles are served through a CDN, so the cluster only spends its time rendering HTML.</p>
<h2>If you are building this today</h2>
<p>The architecture above has held up well, but if I were starting from zero now, I would change two things.</p>
<p>First, I would not build on the community ingress-nginx controller. Kubernetes retired it in March 2026, which means no more releases and no more security fixes. The Kubernetes project recommends Gateway API as the replacement. Everything in this post still applies: hostname routing, a wildcard setup for subdomains, and per-domain certificates through cert-manager. Only the type of routing resource changes.</p>
<p>Second, I would put the hostname on every log line and metric from day one. We added it later, and the weeks before that were the hardest to debug.</p>
<p>The part I would keep exactly the same is the core decision. Treat a customer website as data, keep one well-tested renderer, and put your effort into routing, caching and safe deploys. That is what lets a small team run 100+ websites without the platform growing a new problem with every new customer.</p>
<hr />
<p><em>I'm Usman Hafeez, a System Architect and Full-Stack Tech Lead. I build multi-tenant SaaS platforms on AWS and Kubernetes, and AI agent features with LangChain and LangGraph. More of my work is at</em> <a href="https://usmanhafeez147.vercel.app"><em>usmanhafeez147.vercel.app</em></a><em>.</em></p>
]]></content:encoded></item></channel></rss>