<?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 Mustak Sahariar on Medium]]></title>
        <description><![CDATA[Stories by Mustak Sahariar on Medium]]></description>
        <link>https://medium.com/@msmiraj8?source=rss-243670e2a260------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cbiBP9RTZWAcIvgnxa5JZw.jpeg</url>
            <title>Stories by Mustak Sahariar on Medium</title>
            <link>https://medium.com/@msmiraj8?source=rss-243670e2a260------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 15:02:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msmiraj8/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[Inside NGINX Architecture]]></title>
            <link>https://medium.com/@msmiraj8/inside-nginx-architecture-6b11dbf3ae47?source=rss-243670e2a260------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b11dbf3ae47</guid>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <dc:creator><![CDATA[Mustak Sahariar]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 17:13:07 GMT</pubDate>
            <atom:updated>2026-07-26T17:18:35.487Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Deep Dive into Its Architecture and Request Processing</h4><h4>What is NGINX?</h4><p>NGINX (pronounced “engine-x”) is an open-source software used for web serving, reverse proxying, caching, and load balancing. Pretty simple right? It will make more sense when we’ll understand how Nginx works.</p><figure><img alt="What is NGINX?" src="https://cdn-images-1.medium.com/max/1024/1*ePjf0equWOVMNdd721QoIA.png" /></figure><h4>Web Server vs. Application Server vs. Reverse proxy</h4><p>A web server is a lightweight system designed to listen for incoming network requests and deliver static content. More straightforward — A web server serves files. You ask for `/logo.png`, it reads that file off disk and sends it back. Fast, simple, no logic.</p><p>An application server runs your code, executes business logic, hits a database, and generates responses dynamically. It doesn’t serve files<em>. </em>When you run `node server.js` and your NestJS app listens on port 4000, that’s an application server.</p><p>A reverse proxy sits in front of your web and application servers to shield them and optimize incoming traffic. The client talks only to the proxy; it never knows that there’s a NestJS process behind it. It handles resource-heavy tasks like SSL/TLS decryption, distributes incoming requests across a cluster of backend servers, hides the real IP addresses and internal architecture of your backend systems.</p><p>Why are we discussing all these? Well, Nginx can handle all three at once. Nginx works as a web server (serves static assets directly), forwards API calls to Node process (reverse proxy), and terminates HTTPS on the way in. The application server will not see an unencrypted-vs-encrypted distinction and don’t get exposed directly to the public internet.</p><p><strong>So nginx can work as:</strong></p><ul><li>Reverse proxy</li><li>TLS (SSL) termination</li><li>Web Server (Static File Server)</li><li>Load balancer</li><li>HTTP Request Routing</li><li>API Gateway</li><li>Caching</li><li>Rate limit</li><li>Logging and debugging</li></ul><h4>Architecture: One Master, Many Workers</h4><figure><img alt="NGINX Architecture: Master Workers model" src="https://cdn-images-1.medium.com/max/1024/1*jvgeqAJ1hlURbYDecuTLOQ.png" /><figcaption>Nginx Architecture: Master Workers Model</figcaption></figure><p>So when nginx starts, it spawns a master process and several worker processes (1 worker per CPU core).</p><p><strong>What does the master process do?</strong> It reads the config, binds the privileged ports (80, 443), and manages the lifecycle of the workers. Mostly privileged and administrative jobs. We can call it the supervisor.</p><p><strong>The worker processes do the actual work</strong> — accepting connections, handling HTTP and network traffic. Alongside the worker process there are two specialized helpers: the Cache Manager (CM), which periodically prunes the on-disk cache to keep it within size limits, and the Cache Loader (CL), which runs once at startup to load existing cache metadata into memory and then exits. All these processes coordinate through shared memory — that’s how cache state, rate-limit counters, and session persistence data are visible across workers that are otherwise fully independent.</p><p><strong>The proxy cache</strong> stores responses from upstream application servers on disk. So subsequent identical requests are served directly without hitting your backend. The proxy cache is split across two locations. Its index (the lookup table of what’s cached and whether it’s fresh) lives in shared memory for speed, while the actual cached response bodies are stored on disk. Here comes the cache manager and cache loader. The cache loader reads the on-disk cache into the shared-memory index at startup and the cache manager prunes expired entries from disk in the background.</p><p><strong>Shared memory</strong> is in RAM and is the one region all the workers can see simultaneously. Rate-limit counters live here precisely so every worker enforces the same limit. Static files and logs live entirely on disk and the workers read and write them directly. The proxy cache is the <em>special</em> one because it’s split between shared memory (the index) and disk (the actual content).</p><p><strong>Upstreams</strong> sit outside the process group entirely — they’re separate servers (your NestJS process) and only workers talk to them.</p><h4>Inside a Worker Process</h4><figure><img alt="Worker Process: Single threaded, Event driven" src="https://cdn-images-1.medium.com/max/940/1*w7lnnHEpxApctb3gykmZmQ.png" /><figcaption>Inside The Worker Process (Single thread)</figcaption></figure><p>A single worker isn’t just an event loop; it runs multiple <strong>state machines:</strong></p><ul><li>HTTP State Machine</li><li>Stream State Machine</li><li>Mail State Machine</li></ul><p><strong>The HTTP state machine</strong> handles web traffic, the <strong>Mail state machine</strong> handles email proxying (IMAP/POP3/SMTP), and the <strong>Stream state machine</strong> handles raw TCP/UDP proxying. This is why nginx isn’t only a web server. The same event-driven engine can front a database connection pool or a mail server.</p><p>Now let’s dive inside the HTTP state machine. Here we have the connection set. A worker is <em>holding a large pile of open connections</em>. Each one of them is called client socket. Each connection is stored as a small bundle of data in the worker’s memory. A few kilobytes of data that stores:</p><ul><li><strong>Which client it is</strong> — basically the connection’s ID, so the worker knows which client this is out of the thousands it’s handling.</li><li><strong>How far through its request it’s gotten</strong> — the connection’s progress. Has the worker read the request yet? Is it waiting on the backend? Is it partway through sending the response? Think it this way — a waiter remembers which tables have ordered, which are cooking on the kitchen, and which are ready for the bill.</li><li><strong>Which buffers it’s using</strong> — to make it more simple let’s say where its data is being held. Each connection needs a little space to hold data in transit. The incoming request bytes as they arrive, and the outgoing response bytes on their way out. These holding areas are called buffers. Just to make sure that one client’s data never gets mixed up with another’s.</li></ul><p><strong>A single worker</strong> might hold ten thousand of these at once. That means it can handle thousands of concurrent clients. most of those connections are idle at any given moment. They’re just sitting there waiting on a slow client’s network or being kept open in case the client sends another request soon. An idle connection costs only its few kilobytes of memory and <em>zero</em> CPU while it waits. That’s the key difference from the old model, where every idle connection meant a whole thread frozen in place. Here, a connection is just <em>data the worker remembers</em> — not a thread stuck waiting on it.</p><h4>The Event Loop</h4><figure><img alt="The Event Loop" src="https://cdn-images-1.medium.com/max/981/1*xE1fxtZf-Bh2ERVEICwczw.png" /><figcaption>The Event Loop of Nginx</figcaption></figure><p>Now the problem is a worker has thousands of connections but it is single-threaded. It can only do one thing at a time. <strong>So how on earth it is going to handle thousands of requests?</strong> Here comes the event loop. Event loop means — a cycle the worker repeats over and over — check what needs doing, do it, check again. The “events” are things happening on connections (data arriving, a client ready to receive more).</p><p>Instead of the worker manually checking each of its ten thousand connections one by one (“anything here? anything there? anything to do?” — which would be painfully slow), it offloads that job to the operating system. `epoll` (on Linux) and `kqueue` (on Mac/BSD) are OS features built exactly for this task. The worker hands the whole pile of connections to the kernel and asks one question: <em>“tell me which of these have something ready.”</em></p><p><strong>“Something ready” means one of two things:</strong></p><ul><li>New data arrived — a client sent bytes the worker can now read.</li><li>Room to send more — the outgoing channel has space, so the worker can push more response bytes out.</li></ul><p>The kernel returns only the ready handful. Out of ten thousand connections, maybe fifty have something going on at this instant. The kernel hands back just those fifty. The worker deals with them, then loops back and asks again.</p><p><strong>The event loop is the <em>engine</em> of the worker</strong>, but it doesn’t do the request work itself. Its only job is to <em>decide which connection gets worked on next</em>. It’s the dispatcher, not the worker. It points at the next ready connection and hands it off to the pipeline to actually process.</p><p><strong>The Request Pipeline</strong>. Once the loop points the worker at a ready connection, the worker does the actual work and these steps map directly onto config you’ll write. Depending on the connection’s state, one of these happens: accept a new connection and add start tracking it; read and parse incoming bytes into an HTTP request; match it to a `location` block and run the processing phases (rewrites, rate limits, auth); generate the response by reading a static file, returning a cached response, or proxying to an upstream; then filter, send, and log the response. A connection moves through these stages over time. The pipeline is a sequence of steps but the worker handles each stage as a quick, separate task and jumping between the connections that are ready for <em>next</em> stage rather than escorting one request all the way through. To put it simply — The connection advances through the pipeline in separate little visits, not one continuous escort.</p><h4>The One Place Nginx Uses Threads</h4><p>There’s a catch into the single-threaded design. If a worker ever does something that <em>blocks or </em>stalls the thread then every other connection freezes too. The main culprit is disk I/O. Reading a large file off a slow disk can’t be made truly non-blocking and if the worker stalled on it then thousands of clients would hang.</p><p>Nginx has a small pool of auxiliary threads dedicated to these unavoidably-blocking operations. The worker hands the blocking read to a helper thread and keeps its main event loop free. This is the <em>only</em> place nginx reaches for threads. These threads exist to <em>protect</em> the non-blocking model, not to replace it. It’s the exact opposite of the thread-per-connection model.</p><h4>The Life of an HTTP Request: Phases</h4><p>Once a request reaches a worker, nginx doesn’t just “handle it” in one blob. It runs the request through some phases, in a fixed order. Each phase does one job, and the order is deliberately arranged so the <em>cheap</em> checks happen before the <em>expensive</em> work.</p><p>Reading top to bottom, one request goes through roughly this sequence:</p><ol><li><strong>Read request headers</strong> — nginx reads the incoming request and figures out the basics like what method (GET, POST), what path (/api/users), and which host. If the request came over HTTPS, it&#39;s decrypted right here, before anything else looks at it.</li><li><strong>Identify the config block.</strong> Now that nginx knows the path, it picks <em>which rules to apply.</em> It uses the location matching to figure out <strong>&quot;which part of my config is responsible for this request?&quot;</strong></li><li><strong>Apply rate limits</strong> — nginx checks <strong>“is this client sending too many requests too fast?”</strong> If they’re over the limit, they get rejected right here. Cheaply &amp; early.</li><li><strong>Authentication</strong> — internal and external access control.</li><li><strong>Generate content</strong> — nginx produces the response, either by reading a static file, returning a cached copy, or proxying to your upstream services.</li><li><strong>Response filters, then log</strong> — gzip compression, header manipulation, send it to the client and finally the log entry.</li></ol><p><strong>Quick insight:</strong> Notice where rate-limiting and auth sit, <em>before</em> content generation. That ordering is the whole point. Because the cheap gatekeeping checks run first, a bad request never reaches the expensive part. A flood of requests hitting a `limit_req` ceiling gets rejected at phase 3 — your upstream process never even sees them, never spins up a database query, never spends a CPU cycle on them.</p><h4>Conclusion</h4><p>So let’s summarize the whole situation here. Nginx is a web server, reverse proxy, and TLS terminator rolled into an event-driven architecture that handles massive concurrency on little memory. A master supervises a fleet of workers and each worker holds thousands of connections. Nginx uses an event loop to pick the few that are ready, and runs each through a request pipeline in interleaved fragments, offloading only genuinely-blocking work to a small thread pool. Every request flows through an ordered set of phases, all configured through a tree of contexts with a matching order that rewards understanding over guessing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b11dbf3ae47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started With Prisma 7 with Nest Js & MySQL]]></title>
            <link>https://medium.com/@msmiraj8/get-started-with-prisma-7-with-nest-js-mysql-3919eaa7c760?source=rss-243670e2a260------2</link>
            <guid isPermaLink="false">https://medium.com/p/3919eaa7c760</guid>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Mustak Sahariar]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 18:44:43 GMT</pubDate>
            <atom:updated>2025-11-25T18:44:43.378Z</atom:updated>
            <content:encoded><![CDATA[<p>So what is prisma? It’s an ORM for Node.js and TypeScript which helps us to manage and interact with the database. We can define database models and relations using the prisma schema. With the latest release of Prisma 7 it is now simpler and faster. Not sure about the simpler part btw :3</p><p>Let’s see the changes first.</p><h4>What are the changes?</h4><ul><li>Prisma Client no longer uses native Rust binaries.</li><li>Fully rewritten in TypeScript and runs purely in JS runtimes.</li><li>Generated client code is no longer inside node_modules . Generated types and client output located inside your <strong>project source</strong>.</li><li>No need to restart dev server when regenerating Prisma Client.</li><li>New Prisma config file.</li><li>Require a driver adapter for all database drivers.</li><li>The generated prisma client is <strong>database-agnostic</strong>. It only cares about the <strong>schema structure</strong>, not the database instance.</li><li>New Prisma Studio version (npx prisma studio).</li><li>Support for <strong>mapped enums.</strong></li></ul><p><em>I’ll skip the Nest Js project setup part for now. Let’s just focus on prisma.</em></p><ol><li>First install both the prisma and @prisma/client packages:</li></ol><pre>npm install @prisma/client@7<br>npm install -D prisma@7</pre><p>In Prisma 7, environment variables are not loaded by default. To use the environment variables:</p><pre>npm install dotenv</pre><p>My node and npm version:</p><pre>node -v<br>v24.11.1<br>npm -v<br>11.6.2</pre><p>We’re done with the dependency so far.</p><p>2. Now to create your initial Prisma setup:</p><pre>npx prisma init</pre><p>This will create a new prisma directory with the following files:</p><ul><li>schema.prisma: Specifies your database connection and contains the database schema.</li><li>prisma.config.ts: A configuration file.</li><li>.env: A dotenv file, typically used to store your database credentials.</li></ul><p>3. Now you can ask why do i need an adapter all of a sudden? Well let’s discuss about that at the end of the setup. For now:</p><pre> npm install @prisma/adapter-mariadb</pre><p>4. We have to configure our database URL, schema location, migration output, and custom seed scripts. And an important note from the doc — The prisma.config.ts file should be placed at the root of your project (where your package.json is located).</p><p>.env file:</p><pre>DATABASE_URL=&quot;mysql://test_user:test_password@localhost:3306/test_db&quot;</pre><p>prisma.config.ts file:</p><pre>// This file was generated by Prisma and assumes you have installed the following:<br>// npm install --save-dev prisma dotenv<br>import &quot;dotenv/config&quot;;<br>import { defineConfig, env } from &quot;prisma/config&quot;;<br><br>export default defineConfig({<br>  schema: &quot;prisma/schema.prisma&quot;,<br>  migrations: {<br>    path: &quot;prisma/migrations&quot;,<br>    seed: &#39;tsx prisma/seed.ts&#39;,<br>  },<br>  datasource: {<br>    url: process.env.DATABASE_URL!<br>  },<br>});</pre><p><strong>Faced an issue -</strong> Error:PrismaConfigEnvError: Missing required environment variable: DATABASE_URL , Error: The datasource property is required in your Prisma Config file when using prisma db push.</p><blockquote>Solution : <a href="https://github.com/prisma/prisma/issues/28590">https://github.com/prisma/prisma/issues/28590</a></blockquote><p>5. Here we will specify the output path and define the db schema in prisma.schema :</p><pre>generator client {<br>  provider = &quot;prisma-client&quot;<br>  output   = &quot;../src/generated/prisma&quot;<br>  moduleFormat = &quot;cjs&quot; //Matches Prisma&#39;s output format with NestJS&#39;s CommonJS runtime environment.<br>}<br><br>datasource db {<br>  provider = &quot;mysql&quot;<br>}<br><br>// Example model<br>model user {<br>  id        Int      @id @default(autoincrement())<br>  email     String   @unique<br>  name      String?<br>  password  String<br>  createdAt DateTime @default(now())<br>  updatedAt DateTime @updatedAt<br>}</pre><p>6. NestJS service that wraps Prisma Client to handle the connection lifecycle prisma.service.ts :</p><pre>import { Injectable, OnModuleInit, OnModuleDestroy } from &#39;@nestjs/common&#39;;<br>import { PrismaClient } from &#39;../src/generated/prisma/client&#39;;<br>import { PrismaMariaDb } from &#39;@prisma/adapter-mariadb&#39;;<br><br>@Injectable()<br>export class PrismaService<br>  extends PrismaClient<br>  implements OnModuleInit, OnModuleDestroy<br>{<br>  constructor() {<br>    const adapter = new PrismaMariaDb(process.env.DATABASE_URL!);<br>    super({ adapter, log: [&#39;info&#39;, &#39;warn&#39;, &#39;error&#39;] });<br>  }<br><br>  async onModuleInit() {<br>    try {<br>      await this.$connect();<br>      await this.$queryRaw`SELECT 1`;<br>      console.log(&#39;✅ Prisma connected to MySQL&#39;);<br>    } catch (error) {<br>      console.error(&#39;❌ Prisma connection error:&#39;, error);<br>      throw error;<br>    }<br>  }<br><br>  async onModuleDestroy() {<br>    await this.$disconnect();<br>    console.log(&#39;🔌 Prisma disconnected from MySQL&#39;);<br>  }<br>}</pre><p>7. Now to export PrismaService and make available globally prisma.module.ts :</p><pre>import { Module, Global } from &#39;@nestjs/common&#39;;<br>import { PrismaService } from &#39;./prisma.service&#39;;<br><br>@Global()<br>@Module({<br>  providers: [PrismaService],<br>  exports: [PrismaService],<br>})<br>export class PrismaModule {}</pre><p>8. If you need some test data you needseed.ts :</p><pre>import { PrismaClient } from &#39;../src/generated/prisma/client&#39;;<br>import { PrismaMariaDb } from &#39;@prisma/adapter-mariadb&#39;;<br>import &#39;dotenv/config&#39;;<br><br>const adapter = new PrismaMariaDb(process.env.DATABASE_URL!);<br>const prisma = new PrismaClient({ adapter });<br><br>async function main() {<br>  console.log(&#39;🌱 Starting database seeding...&#39;);<br><br>  // Check if database already has data<br>  const userCount = await prisma.user.count();<br>  <br>  if (userCount &gt; 0) {<br>    console.log(&#39;⚠️  Database already contains data. Skipping seed.&#39;);<br>    console.log(`   Found ${userCount} users in the database.`);<br>    return;<br>  }<br><br>  console.log(&#39;📭 Database is empty. Starting seed...&#39;);<br><br>  // Hash password for users<br>  const hashedPassword = &#39;test12345&#39;;<br><br>  // Create users<br>  const user1 = await prisma.user.create({<br>    data: {<br>      email: &#39;robot@gmail.com&#39;,<br>      name: &#39;Mr Robot&#39;,<br>      password: hashedPassword,<br>    },<br>  });<br><br>  console.log(&#39;✅ Created users&#39;);<br>}<br><br>main()<br>  .catch((e) =&gt; {<br>    console.error(&#39;❌ Error during seeding:&#39;, e);<br>    process.exit(1);<br>  })<br>  .finally(async () =&gt; {<br>    await prisma.$disconnect();<br>  });</pre><p>9. Import the PrismaModule into your main AppModule app.module.ts :</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { AuthModule } from &#39;./modules/auth/auth.module&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { PrismaModule } from &#39;prisma/prisma.module&#39;;<br><br>@Module({<br>  imports: [AuthModule, PrismaModule, ConfigModule.forRoot()],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>Now make sure the database is running and run these commands:</p><pre>npx prisma generate<br>npx prisma db push<br>npx prisma db seed<br>npm run start:dev</pre><p>Add this into your .gitignore :</p><pre>/src/generated</pre><p>Finally the folder structure:</p><pre><br>└── 📁backend<br>    └── 📁prisma<br>        ├── prisma.module.ts<br>        ├── prisma.service.ts<br>        ├── schema.prisma<br>        ├── seed.ts<br>    └── 📁src<br>        └── 📁generated<br>            └── 📁prisma<br>        └── 📁modules<br>            └── 📁auth<br>        ├── app.controller.spec.ts<br>        ├── app.controller.ts<br>        ├── app.module.ts<br>        ├── app.service.ts<br>        ├── main.ts<br>    ├── .env<br>    ├── .gitignore<br>    ├── .prettierrc<br>    ├── eslint.config.mjs<br>    ├── nest-cli.json<br>    ├── package-lock.json<br>    ├── package.json<br>    ├── prisma.config.ts<br>    ├── README.md<br>    ├── tsconfig.build.json<br>    └── tsconfig.json</pre><p>Finally, a GUI tool to visualize your data locally:</p><pre>npx prisma studio</pre><p>Now time to understand the <strong>Driver Adapters</strong></p><p>The previous version of prisma client depended on a <strong>Rust-based Query Engine.</strong> It was responsible for:</p><ul><li>Transforming Prisma Client queries into SQL statements.</li><li>Maintain the connection with the database via TCP using built-in drivers.</li></ul><p>Now Prisma 7 introduced us to query compiler (client engine), running in JS and removed the build-in drivers that were inside the Rust binary. Now we have to use JavaScript database drivers to connect and run queries against the database. And as a translator between the Query Engine/Compiler &amp; the Database Driver we need Driver Adapters. For MySQL we have to use mariadb adapter. <a href="https://www.prisma.io/docs/orm/overview/databases/database-drivers#database-driver-adapters:~:text=prisma/adapter%2Dppg-,MySQL/MariaDB,mariadb,-SQLite">To learn more visit…</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ympg4e32svA71wJP7vBPeQ.png" /><figcaption>Source: <a href="https://www.prisma.io/docs/orm/overview/databases/database-drivers#database-driver-adapters">prisma docs</a></figcaption></figure><p>That should do for now. Please let me know if I’ve missed something.</p><blockquote>“Trust logs.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3919eaa7c760" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>