<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: SudoSecurity</title>
    <description>The latest articles on DEV Community by SudoSecurity (@sudosecurity).</description>
    <link>https://dev.to/sudosecurity</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4242213%2F23f42175-6cf2-4049-b570-7d00ec120431.png</url>
      <title>DEV Community: SudoSecurity</title>
      <link>https://dev.to/sudosecurity</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sudosecurity"/>
    <language>en</language>
    <item>
      <title>The JavaScript Event Loop: Call Stack, Task Queue &amp; Microtasks</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Fri, 27 Nov 2026 14:00:02 +0000</pubDate>
      <link>https://dev.to/sudosecurity/the-javascript-event-loop-call-stack-task-queue-microtasks-1dnn</link>
      <guid>https://dev.to/sudosecurity/the-javascript-event-loop-call-stack-task-queue-microtasks-1dnn</guid>
      <description>&lt;p&gt;&lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; runs on a single thread. That thread has one call stack, one memory heap, and one thing it can execute at any given moment. Yet a properly written &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; server handles tens of thousands of concurrent connections without spawning a thread per request, without blocking, and without the kind of concurrency bugs that plague multi-threaded systems in Java or C++.&lt;/p&gt;

&lt;p&gt;The mechanism behind that is the event loop. Every &lt;code&gt;setTimeout&lt;/code&gt;, every &lt;code&gt;await&lt;/code&gt;, every &lt;code&gt;.then()&lt;/code&gt;, every &lt;code&gt;fs.readFile&lt;/code&gt; callback — all of it runs because the event loop coordinates when JavaScript code actually executes. If you do not understand the event loop at a mechanical level, you will write bugs that only appear under production load, bugs that are nearly impossible to reproduce locally, and bugs where your logging shows no obvious error but requests hang or return stale data.&lt;/p&gt;

&lt;p&gt;This article walks through the event loop from first principles to production-grade async patterns. Every code sample is the kind you would write in a real backend service, not a toy example.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Call Stack
&lt;/h2&gt;

&lt;p&gt;When &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; calls a function, the runtime pushes an execution context onto the call stack. That context holds the function's local variables, its arguments, and a return address pointing back to the calling code. When the function returns, its context pops off the stack. The stack is LIFO — last in, first out.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createServer, IncomingMessage, ServerResponse } from 'http';
import { URL } from 'url';

function extractPathSegments(rawUrl: string, base: string): string[] {
  const url = new URL(rawUrl, base);
  return url.pathname.split('/').filter(Boolean);
}

function buildRouteKey(method: string, segments: string[]): string {
  const normalized = segments.map((s) =&amp;gt; (/^\d+$/.test(s) ? ':id' : s));
  return `${method.toUpperCase()} /${normalized.join('/')}`;
}

function resolveRoute(req: IncomingMessage): string {
  const segments = extractPathSegments(req.url ?? '/', 'http://localhost');
  return buildRouteKey(req.method ?? 'GET', segments);
}

const server = createServer((req: IncomingMessage, res: ServerResponse) =&amp;gt; {
  const routeKey = resolveRoute(req);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(routeKey);
});

server.listen(3000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When a request arrives and &lt;code&gt;resolveRoute&lt;/code&gt; is called, the call stack builds up in layers: the &lt;code&gt;createServer&lt;/code&gt; callback at the bottom, then &lt;code&gt;resolveRoute&lt;/code&gt;, then &lt;code&gt;extractPathSegments&lt;/code&gt;, then the &lt;code&gt;URL&lt;/code&gt; constructor deep inside. The stack unwinds in reverse as each function returns. At no point does &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; execute two of these functions simultaneously. &lt;code&gt;buildRouteKey&lt;/code&gt; does not start until &lt;code&gt;extractPathSegments&lt;/code&gt; returns. &lt;code&gt;resolveRoute&lt;/code&gt; does not return until &lt;code&gt;buildRouteKey&lt;/code&gt; returns.&lt;/p&gt;

&lt;p&gt;This sequential, deterministic execution within synchronous code is the foundation everything else builds on. The call stack is not concurrent. It is a strict execution order enforced by the runtime.&lt;/p&gt;

&lt;p&gt;The stack has a hard size limit determined by the engine and the available memory. Unbounded recursion exhausts it. In V8 (the engine used by &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; and Chrome), the limit is typically around 10,000–15,000 frames depending on frame size. Hitting that limit throws a &lt;code&gt;RangeError: Maximum call stack size exceeded&lt;/code&gt; and crashes the current execution context.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Blocking the Stack Destroys Server Performance
&lt;/h2&gt;

&lt;p&gt;Because &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; has one thread and one call stack, any synchronous operation that takes time blocks every other operation from running. There is no scheduler. There is no OS-level preemption. The event loop cannot move to the next task until the call stack is empty.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { readFileSync, readdirSync } from 'fs';
import { createServer, IncomingMessage, ServerResponse } from 'http';

interface ConfigFile {
  name: string;
  content: Record&amp;lt;string, unknown&amp;gt;;
}

function loadAllConfigs(configDir: string): ConfigFile[] {
  const files = readdirSync(configDir);
  return files
    .filter((f) =&amp;gt; f.endsWith('.json'))
    .map((file) =&amp;gt; {
      const raw = readFileSync(`${configDir}/${file}`, 'utf8');
      return {
        name: file,
        content: JSON.parse(raw) as Record&amp;lt;string, unknown&amp;gt;,
      };
    });
}

const server = createServer((_req: IncomingMessage, res: ServerResponse) =&amp;gt; {
  const configs = loadAllConfigs('./config');
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(configs));
});

server.listen(3000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;readdirSync&lt;/code&gt; and &lt;code&gt;readFileSync&lt;/code&gt; are synchronous filesystem calls. They tell the OS to read from disk, then block the &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; thread until the OS returns the data. During that blocking period — which might be 1ms on a warm OS cache or 50ms on a cold HDD — every other incoming &lt;a href="https://sudosecurity.org/your-https-is-toast/" rel="noopener noreferrer"&gt;HTTP&lt;/a&gt; connection sits waiting. No other request handler runs. No timer callbacks fire. No database responses get processed. The single thread is occupied waiting for the filesystem.&lt;/p&gt;

&lt;p&gt;A server handling 500 concurrent requests where each request blocks for 10ms on config reads is, in practice, a server that can only serve 2 requests per second despite having idle CPU cores. The CPU is not the bottleneck. The single blocked thread is.&lt;/p&gt;

&lt;p&gt;This is why &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; exposes async versions of every &lt;code&gt;I/O&lt;/code&gt; operation and why you should never call the sync variants inside request handlers. &lt;code&gt;readFileSync&lt;/code&gt; is appropriate in build scripts and CLI tools that run once. It has no place in a server.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Event Loop's Role: Web APIs and the Task Queue
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; itself does not perform &lt;code&gt;I/O&lt;/code&gt;. The runtime environment — &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;, the browser — provides APIs that delegate &lt;code&gt;I/O&lt;/code&gt; to the operating system using non-blocking system calls (&lt;code&gt;epoll&lt;/code&gt; on Linux, &lt;code&gt;kqueue&lt;/code&gt; on macOS, IOCP on Windows). &lt;code&gt;libuv&lt;/code&gt;, the library under &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;, abstracts these into a unified async &lt;code&gt;I/O&lt;/code&gt; model.&lt;/p&gt;

&lt;p&gt;When you call &lt;code&gt;fs.readFile&lt;/code&gt;, &lt;code&gt;setTimeout&lt;/code&gt;, &lt;code&gt;fetch&lt;/code&gt;, or &lt;code&gt;net.connect&lt;/code&gt;, you hand work off to the runtime. Node.j pushes the call onto the stack, the runtime registers the operation with the OS, and then pops the call off the stack and keeps executing. The OS does the actual work — reading disk sectors, waiting for a network packet — while &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt;'s thread continues processing other code.&lt;/p&gt;

&lt;p&gt;When the OS finishes the operation, it signals &lt;code&gt;libuv&lt;/code&gt;, which places the callback you provided into the &lt;strong&gt;task queue&lt;/strong&gt; (also called the macrotask queue or callback queue). The event loop then checks: if the call stack is empty, dequeue one task and push it onto the stack for execution.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { readFile } from 'fs/promises';
import { createServer, IncomingMessage, ServerResponse } from 'http';
import path from 'path';

const ALLOWED_EXTENSIONS = new Set(['.json', '.txt', '.html']);

async function readSafeFile(filename: string, baseDir: string): Promise&amp;lt;string&amp;gt; {
  const resolvedBase = path.resolve(baseDir);
  const resolvedTarget = path.resolve(baseDir, filename);

  if (!resolvedTarget.startsWith(resolvedBase)) {
    throw new RangeError(`Path traversal attempt: ${filename}`);
  }

  const ext = path.extname(filename);
  if (!ALLOWED_EXTENSIONS.has(ext)) {
    throw new TypeError(`Disallowed file type: ${ext}`);
  }

  return readFile(resolvedTarget, 'utf8');
}

const server = createServer(async (req: IncomingMessage, res: ServerResponse) =&amp;gt; {
  const url = new URL(req.url ?? '/', 'http://localhost');
  const filename = url.searchParams.get('file') ?? '';

  if (!filename) {
    res.writeHead(400);
    res.end('Missing file parameter');
    return;
  }

  try {
    const content = await readSafeFile(filename, path.join(process.cwd(), 'public'));
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(content);
  } catch (err) {
    if (err instanceof RangeError || err instanceof TypeError) {
      res.writeHead(403);
      res.end(err.message);
    } else {
      res.writeHead(500);
      res.end('Internal server error');
    }
  }
});

server.listen(3000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;readFile&lt;/code&gt; from &lt;code&gt;fs/promises&lt;/code&gt; returns a Promise backed by &lt;code&gt;libuv&lt;/code&gt;'s async file &lt;code&gt;I/O&lt;/code&gt;. When you &lt;code&gt;await&lt;/code&gt; it, &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; suspends execution of the async function and frees the call stack. The thread continues processing other requests, timer callbacks, or database responses. When the OS finishes reading the file, &lt;code&gt;libuv&lt;/code&gt; places the Promise resolution into the microtask queue, and the async function resumes from where it paused.&lt;/p&gt;

&lt;p&gt;Notice the path traversal guard. &lt;code&gt;path.resolve&lt;/code&gt; canonicalizes the path before comparing it to the base directory. A filename like &lt;code&gt;../../etc/passwd&lt;/code&gt; resolves to a path outside &lt;code&gt;baseDir&lt;/code&gt;, and the check catches it before touching the filesystem. Async &lt;code&gt;I/O&lt;/code&gt; does not make your code safe by itself — it just makes it non-blocking. Security checks are still your responsibility.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Microtask Queue: Higher Priority Than Everything Else
&lt;/h2&gt;

&lt;p&gt;The task queue holds callbacks from timers, &lt;code&gt;I/O&lt;/code&gt;, and system events. Promises use a separate, higher-priority queue: the &lt;strong&gt;microtask queue&lt;/strong&gt;. The event loop drains the entire microtask queue before it picks up the next &lt;code&gt;macrotask&lt;/code&gt;. Every &lt;code&gt;.then()&lt;/code&gt; callback, every &lt;code&gt;await&lt;/code&gt; continuation, every &lt;code&gt;queueMicrotask()&lt;/code&gt; call lands in the microtask queue.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { EventEmitter } from 'events';

class AsyncJobQueue extends EventEmitter {
  private queue: Array&amp;lt;() =&amp;gt; Promise&amp;lt;void&amp;gt;&amp;gt; = [];
  private running = false;

  enqueue(job: () =&amp;gt; Promise&amp;lt;void&amp;gt;): void {
    this.queue.push(job);
    queueMicrotask(() =&amp;gt; this.drain());
  }

  private async drain(): Promise&amp;lt;void&amp;gt; {
    if (this.running) return;
    this.running = true;

    while (this.queue.length &amp;gt; 0) {
      const job = this.queue.shift()!;
      try {
        await job();
        this.emit('job:complete');
      } catch (err) {
        this.emit('job:error', err);
      }
    }

    this.running = false;
    this.emit('queue:empty');
  }
}

const jobQueue = new AsyncJobQueue();

jobQueue.on('job:complete', () =&amp;gt; {
  console.log('job finished');
});

jobQueue.on('queue:empty', () =&amp;gt; {
  console.log('all jobs processed');
});

jobQueue.on('job:error', (err: Error) =&amp;gt; {
  console.error('job failed:', err.message);
});

jobQueue.enqueue(async () =&amp;gt; {
  await new Promise&amp;lt;void&amp;gt;((resolve) =&amp;gt; setTimeout(resolve, 100));
  console.log('job A');
});

jobQueue.enqueue(async () =&amp;gt; {
  console.log('job B');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;queueMicrotask(() =&amp;gt; this.drain())&lt;/code&gt; schedules &lt;code&gt;drain&lt;/code&gt; as a microtask rather than calling it immediately. This matters for two reasons. First, it prevents re-entrant calls to &lt;code&gt;drain&lt;/code&gt; when &lt;code&gt;enqueue&lt;/code&gt; is called from inside a job. Second, if multiple jobs are enqueued synchronously in the same turn of the event loop, all of them land in &lt;code&gt;this.queue&lt;/code&gt; before &lt;code&gt;drain&lt;/code&gt; starts. &lt;code&gt;drain&lt;/code&gt; then processes the batch rather than getting called once per job and thrashing the &lt;code&gt;running&lt;/code&gt; lock.&lt;/p&gt;

&lt;p&gt;The microtask queue runs to completion before the next &lt;code&gt;macrotask&lt;/code&gt;. That means the &lt;code&gt;drain&lt;/code&gt; microtask fires after all synchronous code in the current turn finishes, but before any &lt;code&gt;setTimeout&lt;/code&gt; callback. The &lt;code&gt;while&lt;/code&gt; loop inside &lt;code&gt;drain&lt;/code&gt; keeps processing jobs as long as the queue has items. Each &lt;code&gt;await job()&lt;/code&gt; pauses the async function, but between awaits the event loop can process other pending microtasks. It cannot process new &lt;code&gt;I/O&lt;/code&gt; callbacks or timer callbacks until &lt;code&gt;drain&lt;/code&gt; returns or hits an &lt;code&gt;await&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Emitting events synchronously from within an async function is intentional here. &lt;code&gt;EventEmitter.emit&lt;/code&gt; is synchronous — all listeners for &lt;code&gt;job:complete&lt;/code&gt; run before &lt;code&gt;emit&lt;/code&gt; returns. This makes the event timing predictable: listeners fire immediately after each job, not after the entire batch.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/writing-your-own-api-from-scratch-in-typescript/" rel="noopener noreferrer"&gt;Writing Your Own API From Scratch in TypeScript&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Execution Order: Putting the Queues Together
&lt;/h2&gt;

&lt;p&gt;Understanding the exact order in which microtasks and macrotasks fire is not an academic exercise. It determines whether a cache invalidation fires before or after a database write, whether a cleanup handler runs before a response is sent, and whether a rate limit counter updates before or after you check it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createClient } from 'redis';

type RequestPhase = 'start' | 'cache-miss' | 'db-query' | 'cache-set' | 'response';

interface TraceEvent {
  phase: RequestPhase;
  timestamp: number;
  source: 'sync' | 'microtask' | 'macrotask';
}

async function traceRequestPipeline(
  redis: ReturnType&amp;lt;typeof createClient&amp;gt;,
  userId: number,
): Promise&amp;lt;TraceEvent[]&amp;gt; {
  const trace: TraceEvent[] = [];
  const now = () =&amp;gt; performance.now();

  trace.push({ phase: 'start', timestamp: now(), source: 'sync' });

  const cached = await redis.get(`user:${userId}`);

  if (cached !== null) {
    trace.push({ phase: 'response', timestamp: now(), source: 'microtask' });
    return trace;
  }

  trace.push({ phase: 'cache-miss', timestamp: now(), source: 'microtask' });

  const dbResult = await new Promise&amp;lt;string&amp;gt;((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve(JSON.stringify({ id: userId, name: 'Alice' }));
    }, 0);
  });

  trace.push({ phase: 'db-query', timestamp: now(), source: 'macrotask' });

  await redis.set(`user:${userId}`, dbResult, { EX: 300 });

  trace.push({ phase: 'cache-set', timestamp: now(), source: 'microtask' });

  Promise.resolve().then(() =&amp;gt; {
    trace.push({ phase: 'response', timestamp: now(), source: 'microtask' });
  });

  return trace;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Walk through the execution order. The &lt;code&gt;trace.push({ phase: 'start' })&lt;/code&gt; call runs synchronously — it is plain &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; on the call stack. &lt;code&gt;await redis.get(...)&lt;/code&gt; suspends the async function and surrenders the call stack. The Redis client sends a command over TCP and returns a Promise. When Redis responds, &lt;code&gt;libuv&lt;/code&gt; resolves the Promise and queues the continuation as a microtask. The async function resumes at the &lt;code&gt;if (cached !== null)&lt;/code&gt; line — this is a microtask continuation, so it runs before any pending &lt;code&gt;setTimeout&lt;/code&gt; callbacks.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;setTimeout(() =&amp;gt; resolve(...), 0)&lt;/code&gt; wrapping the simulated DB query places a callback in the &lt;code&gt;macrotask&lt;/code&gt; queue. The async function awaits the Promise wrapping that callback. After the &lt;code&gt;await&lt;/code&gt;, the event loop sees an empty call stack, drains microtasks (none pending), then picks up the &lt;code&gt;setTimeout&lt;/code&gt; callback from the &lt;code&gt;macrotask&lt;/code&gt; queue, which resolves the Promise. The async function's next continuation queues as a microtask and runs before any other &lt;code&gt;macrotask&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This trace makes the queue priority visible. Everything after an &lt;code&gt;await redis.get&lt;/code&gt; is a microtask continuation. Everything after an &lt;code&gt;await new Promise(resolve =&amp;gt; setTimeout(...))&lt;/code&gt; is a &lt;code&gt;macrotask&lt;/code&gt;continuation followed immediately by a microtask continuation.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Right Way to Handle Database &lt;code&gt;I/O&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Every &lt;code&gt;await pool.query(...)&lt;/code&gt; in your application does not open a new TCP connection to your database. It borrows a connection from a pool, runs the query, and returns the connection. Opening a TCP connection costs a TLS handshake, a database authentication round-trip, and typically 20–100ms of wall-clock time. At 1,000 requests per second, paying that cost per query means 20–100 seconds of connection overhead per second of traffic — a math problem that cannot be solved by adding servers.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Pool, PoolClient, DatabaseError } from 'pg';
import { createLogger } from 'winston';

const logger = createLogger({ level: 'info' });

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,
  min: 5,
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 3_000,
  statement_timeout: 10_000,
  application_name: 'api-server',
});

pool.on('error', (err: Error) =&amp;gt; {
  logger.error({ err }, 'Idle client error in pool');
});

pool.on('connect', () =&amp;gt; {
  logger.info({ totalCount: pool.totalCount, idleCount: pool.idleCount }, 'Pool connection established');
});

interface TransactionResult&amp;lt;T&amp;gt; {
  data: T;
  durationMs: number;
}

async function withTransaction&amp;lt;T&amp;gt;(
  fn: (client: PoolClient) =&amp;gt; Promise&amp;lt;T&amp;gt;,
): Promise&amp;lt;TransactionResult&amp;lt;T&amp;gt;&amp;gt; {
  const client = await pool.connect();
  const start = performance.now();

  try {
    await client.query('BEGIN');
    const data = await fn(client);
    await client.query('COMMIT');
    return { data, durationMs: performance.now() - start };
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

interface UserRow {
  id: number;
  username: string;
  email: string;
  role: 'admin' | 'member' | 'viewer';
  created_at: Date;
}

interface AuditRow {
  user_id: number;
  action: string;
  performed_by: number;
  performed_at: Date;
}

async function promoteUserToAdmin(
  userId: number,
  requesterId: number,
): Promise&amp;lt;UserRow&amp;gt; {
  const { data: user } = await withTransaction(async (client) =&amp;gt; {
    const userResult = await client.query&amp;lt;UserRow&amp;gt;(
      `SELECT id, username, email, role, created_at
       FROM users
       WHERE id = $1
         AND deleted_at IS NULL
       FOR UPDATE`,
      [userId],
    );

    if (userResult.rowCount === 0) {
      throw Object.assign(new Error('User not found'), { code: 'USER_NOT_FOUND' });
    }

    const target = userResult.rows[0];

    if (target.role === 'admin') {
      throw Object.assign(new Error('User is already an admin'), { code: 'ALREADY_ADMIN' });
    }

    const updated = await client.query&amp;lt;UserRow&amp;gt;(
      `UPDATE users
       SET role = 'admin', updated_at = NOW()
       WHERE id = $1
       RETURNING id, username, email, role, created_at`,
      [userId],
    );

    await client.query&amp;lt;AuditRow&amp;gt;(
      `INSERT INTO audit_log (user_id, action, performed_by, performed_at)
       VALUES ($1, $2, $3, NOW())`,
      [userId, 'PROMOTE_TO_ADMIN', requesterId],
    );

    return updated.rows[0];
  });

  return user;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;withTransaction&lt;/code&gt; wrapper handles three things that production code requires and examples typically skip. First, it acquires a single client from the pool and holds it for the entire transaction. A &lt;code&gt;BEGIN&lt;/code&gt; on one client followed by a query on a different client is not a transaction — it is two separate operations on two separate database sessions. The &lt;code&gt;fn&lt;/code&gt; callback receives the specific client so every query inside the transaction goes to the same connection.&lt;/p&gt;

&lt;p&gt;Second, the &lt;code&gt;FOR UPDATE&lt;/code&gt; lock on the &lt;code&gt;SELECT&lt;/code&gt; prevents a race condition where two concurrent requests both read the user as non-admin, both decide to promote, and both try to write. PostgreSQL serializes writers on a &lt;code&gt;FOR UPDATE&lt;/code&gt; lock. The second concurrent request blocks at the &lt;code&gt;SELECT FOR UPDATE&lt;/code&gt; until the first transaction commits or rolls back, then re-reads the updated row.&lt;/p&gt;

&lt;p&gt;Third, the &lt;code&gt;finally&lt;/code&gt; block releases the client unconditionally. If &lt;code&gt;fn&lt;/code&gt; throws, &lt;code&gt;ROLLBACK&lt;/code&gt; fires, then &lt;code&gt;client.release()&lt;/code&gt; fires. Without &lt;code&gt;finally&lt;/code&gt;, a thrown error returns the client to neither the transaction rollback nor the pool. The pool slowly exhausts its connections as each one leaks. Under sustained error conditions, the application stops accepting database connections entirely.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;statement_timeout: 10_000&lt;/code&gt; in the pool configuration kills any query that takes longer than 10 seconds. Without this, a slow query holds its pool client indefinitely, and a small number of slow queries can exhaust the pool and cascade into full application unavailability.&lt;/p&gt;

&lt;h2&gt;
  
  
  Parallel vs. Sequential Await: Performance Implications
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;await&lt;/code&gt; inside a &lt;code&gt;for&lt;/code&gt; loop runs each operation sequentially. The second iteration does not start until the first completes. This is correct when each operation depends on the previous result and catastrophically slow when operations are independent.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Pool } from 'pg';
import { createClient } from 'redis';

interface UserProfile {
  id: number;
  username: string;
  email: string;
  postsCount: number;
  followersCount: number;
  lastActiveAt: Date | null;
}

interface BatchProfileResult {
  profiles: UserProfile[];
  notFound: number[];
  durationMs: number;
}

async function fetchUserProfilesBatch(
  userIds: number[],
  pool: Pool,
  redis: ReturnType&amp;lt;typeof createClient&amp;gt;,
): Promise&amp;lt;BatchProfileResult&amp;gt; {
  const start = performance.now();

  if (userIds.length === 0) {
    return { profiles: [], notFound: [], durationMs: 0 };
  }

  const deduplicated = [...new Set(userIds)];

  const cacheKeys = deduplicated.map((id) =&amp;gt; `profile:${id}`);
  const cached = await redis.mGet(cacheKeys);

  const cachedProfiles: UserProfile[] = [];
  const uncachedIds: number[] = [];

  cached.forEach((value, index) =&amp;gt; {
    if (value !== null) {
      cachedProfiles.push(JSON.parse(value) as UserProfile);
    } else {
      uncachedIds.push(deduplicated[index]);
    }
  });

  if (uncachedIds.length === 0) {
    return {
      profiles: cachedProfiles,
      notFound: [],
      durationMs: performance.now() - start,
    };
  }

  const placeholders = uncachedIds.map((_, i) =&amp;gt; `$${i + 1}`).join(', ');

  const [usersResult, statsResult] = await Promise.all([
    pool.query&amp;lt;Pick&amp;lt;UserProfile, 'id' | 'username' | 'email'&amp;gt;&amp;gt;(
      `SELECT id, username, email
       FROM users
       WHERE id = ANY(ARRAY[${placeholders}]::int[])
         AND deleted_at IS NULL`,
      uncachedIds,
    ),
    pool.query&amp;lt;{ user_id: number; posts_count: number; followers_count: number; last_active_at: Date | null }&amp;gt;(
      `SELECT
         user_id,
         COUNT(DISTINCT p.id)::int AS posts_count,
         COUNT(DISTINCT f.follower_id)::int AS followers_count,
         MAX(s.last_active_at) AS last_active_at
       FROM users u
       LEFT JOIN posts p ON p.author_id = u.id AND p.deleted_at IS NULL
       LEFT JOIN follows f ON f.followed_id = u.id
       LEFT JOIN user_sessions s ON s.user_id = u.id
       WHERE u.id = ANY(ARRAY[${placeholders}]::int[])
       GROUP BY u.id`,
      uncachedIds,
    ),
  ]);

  const statsMap = new Map(
    statsResult.rows.map((row) =&amp;gt; [row.user_id, row]),
  );

  const foundIds = new Set(usersResult.rows.map((u) =&amp;gt; u.id));
  const notFound = uncachedIds.filter((id) =&amp;gt; !foundIds.has(id));

  const freshProfiles: UserProfile[] = usersResult.rows.map((user) =&amp;gt; {
    const stats = statsMap.get(user.id);
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      postsCount: stats?.posts_count ?? 0,
      followersCount: stats?.followers_count ?? 0,
      lastActiveAt: stats?.last_active_at ?? null,
    };
  });

  if (freshProfiles.length &amp;gt; 0) {
    const pipeline = redis.multi();
    for (const profile of freshProfiles) {
      pipeline.setEx(`profile:${profile.id}`, 300, JSON.stringify(profile));
    }
    await pipeline.exec();
  }

  return {
    profiles: [...cachedProfiles, ...freshProfiles],
    notFound,
    durationMs: performance.now() - start,
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The cache layer uses &lt;code&gt;redis.mGet&lt;/code&gt; — one round-trip to Redis for all keys simultaneously — rather than a &lt;code&gt;for&lt;/code&gt; loop calling &lt;code&gt;redis.get&lt;/code&gt; for each key. For 50 user IDs, &lt;code&gt;mGet&lt;/code&gt; costs one network round-trip. A &lt;code&gt;for&lt;/code&gt; loop with &lt;code&gt;await redis.get&lt;/code&gt; costs 50 sequential round-trips. On a Redis instance with 0.5ms latency, that difference is 0.5ms versus 25ms.&lt;/p&gt;

&lt;p&gt;The database queries run through &lt;code&gt;Promise.all&lt;/code&gt;. The &lt;code&gt;users&lt;/code&gt; query and the aggregated &lt;code&gt;stats&lt;/code&gt; query are independent — neither result feeds into the other query's parameters. Running them in parallel means the total database wait time equals the slower query rather than both queries added together. For queries averaging 8ms and 15ms respectively, sequential execution costs 23ms. Parallel execution costs 15ms.&lt;/p&gt;

&lt;p&gt;The cache writes use a Redis pipeline. A &lt;code&gt;multi()&lt;/code&gt; pipeline batches all &lt;code&gt;SETEX&lt;/code&gt; commands into a single TCP write to Redis and reads a single response. Writing 20 cache entries sequentially costs 20 round-trips; pipelining costs one.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;[...new Set(userIds)]&lt;/code&gt; deduplicates the input before any &lt;code&gt;I/O&lt;/code&gt;. A caller requesting &lt;code&gt;[1, 1, 2, 3, 3]&lt;/code&gt; should not trigger two identical cache checks and two identical database rows for user 1. Deduplication before the first &lt;code&gt;await&lt;/code&gt; costs microseconds and prevents redundant &lt;code&gt;I/O&lt;/code&gt; that scales with input size.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;Promise.allSettled&lt;/code&gt; for Fault-Tolerant Concurrent Operations
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Promise.all&lt;/code&gt; rejects immediately when any of its input Promises reject. For operations where partial success is acceptable — sending notifications, pre-warming caches, firing webhooks — you want results from every operation, not an all-or-nothing outcome.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import nodemailer from 'nodemailer';
import { Pool } from 'pg';
import { createLogger } from 'winston';

const logger = createLogger({ level: 'info' });

interface NotificationTarget {
  userId: number;
  email: string;
  displayName: string;
}

interface NotificationPayload {
  subject: string;
  htmlBody: string;
  textBody: string;
}

interface NotificationResult {
  userId: number;
  status: 'sent' | 'failed';
  error?: string;
  messageId?: string;
}

interface BulkNotificationReport {
  total: number;
  sent: number;
  failed: number;
  results: NotificationResult[];
  durationMs: number;
}

async function sendBulkNotifications(
  targets: NotificationTarget[],
  payload: NotificationPayload,
  pool: Pool,
  transporter: nodemailer.Transporter,
  concurrencyLimit = 25,
): Promise&amp;lt;BulkNotificationReport&amp;gt; {
  const start = performance.now();

  async function sendToUser(target: NotificationTarget): Promise&amp;lt;NotificationResult&amp;gt; {
    const info = await transporter.sendMail({
      from: `"${process.env.EMAIL_FROM_NAME}" &amp;lt;${process.env.EMAIL_FROM_ADDRESS}&amp;gt;`,
      to: `"${target.displayName}" &amp;lt;${target.email}&amp;gt;`,
      subject: payload.subject,
      html: payload.htmlBody,
      text: payload.textBody,
    });

    await pool.query(
      `INSERT INTO notification_log (user_id, subject, message_id, sent_at)
       VALUES ($1, $2, $3, NOW())`,
      [target.userId, payload.subject, info.messageId],
    );

    return { userId: target.userId, status: 'sent', messageId: info.messageId };
  }

  const allResults: NotificationResult[] = [];

  for (let i = 0; i &amp;lt; targets.length; i += concurrencyLimit) {
    const batch = targets.slice(i, i + concurrencyLimit);

    const settled = await Promise.allSettled(batch.map(sendToUser));

    for (const outcome of settled) {
      if (outcome.status === 'fulfilled') {
        allResults.push(outcome.value);
      } else {
        const target = batch[settled.indexOf(outcome)];
        const errorMessage = outcome.reason instanceof Error
          ? outcome.reason.message
          : String(outcome.reason);

        logger.warn(
          { userId: target.userId, email: target.email, error: errorMessage },
          'Notification delivery failed',
        );

        allResults.push({
          userId: target.userId,
          status: 'failed',
          error: errorMessage,
        });
      }
    }
  }

  const sent = allResults.filter((r) =&amp;gt; r.status === 'sent').length;

  return {
    total: targets.length,
    sent,
    failed: targets.length - sent,
    results: allResults,
    durationMs: performance.now() - start,
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The outer &lt;code&gt;for&lt;/code&gt; loop batches targets into groups of &lt;code&gt;concurrencyLimit&lt;/code&gt; (default 25). Within each batch, &lt;code&gt;Promise.allSettled&lt;/code&gt; fires all 25 sends concurrently and waits for all 25 to either fulfill or reject. The loop then starts the next batch of 25. This pattern bounds the number of in-flight SMTP connections and database queries at any given time.&lt;/p&gt;

&lt;p&gt;Without the batch limit, &lt;code&gt;targets.map(sendToUser)&lt;/code&gt; on 10,000 users creates 10,000 simultaneous SMTP connections. Most SMTP providers rate-limit or block at those volumes. A connection pool for SMTP typically caps at 5–10 connections. Opening 10,000 overwhelms it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Promise.allSettled&lt;/code&gt; returns an array of result descriptors, each with a &lt;code&gt;status&lt;/code&gt; field of either &lt;code&gt;'fulfilled'&lt;/code&gt; or &lt;code&gt;'rejected'&lt;/code&gt;. For &lt;code&gt;'fulfilled'&lt;/code&gt; results, &lt;code&gt;outcome.value&lt;/code&gt; is the resolved value. For &lt;code&gt;'rejected'&lt;/code&gt; results, &lt;code&gt;outcome.reason&lt;/code&gt; is the rejection reason. The settled array preserves the same order and length as the input array, so &lt;code&gt;settled.indexOf(outcome)&lt;/code&gt; correctly maps a failed result back to its input &lt;code&gt;target&lt;/code&gt;. This is important for logging — you need the user's ID and email to diagnose delivery failures.&lt;/p&gt;

&lt;p&gt;The database insert inside &lt;code&gt;sendToUser&lt;/code&gt; runs after the SMTP send. If the SMTP send throws, the insert never happens — you do not log a notification you did not send. If the SMTP send succeeds but the database insert throws, &lt;code&gt;sendToUser&lt;/code&gt; rejects with the database error and &lt;code&gt;allSettled&lt;/code&gt; records it as a failure. You sent the email but did not log it; the caller's report shows &lt;code&gt;status: 'failed'&lt;/code&gt;. This is a trade-off. For strict audit requirements, you would use a transactional outbox pattern that records intent before sending and confirms delivery after.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rate Limiting with Atomic Redis Operations
&lt;/h2&gt;

&lt;p&gt;Rate limiting requires reading a counter, deciding whether to allow the request, and incrementing the counter — ideally as an atomic operation. Any gap between reading and writing is a race window.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createClient, Script } from 'redis';
import { createServer, IncomingMessage, ServerResponse } from 'http';

interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  resetAt: number;
  retryAfter?: number;
}

interface RateLimitConfig {
  maxRequests: number;
  windowSeconds: number;
}

const RATE_LIMIT_SCRIPT = `
  local key = KEYS[1]
  local max = tonumber(ARGV[1])
  local window = tonumber(ARGV[2])
  local now = tonumber(ARGV[3])

  local count = redis.call('GET', key)

  if count == false then
    redis.call('SET', key, 1, 'EX', window)
    return {1, max - 1, now + window, 0}
  end

  count = tonumber(count)

  if count &amp;gt;= max then
    local ttl = redis.call('TTL', key)
    return {0, 0, now + ttl, now + ttl}
  end

  redis.call('INCR', key)
  local ttl = redis.call('TTL', key)
  return {1, max - count - 1, now + ttl, 0}
`;

class RateLimiter {
  private readonly redis: ReturnType&amp;lt;typeof createClient&amp;gt;;
  private readonly config: RateLimitConfig;
  private scriptSha: string | null = null;

  constructor(redis: ReturnType&amp;lt;typeof createClient&amp;gt;, config: RateLimitConfig) {
    this.redis = redis;
    this.config = config;
  }

  async check(identifier: string): Promise&amp;lt;RateLimitResult&amp;gt; {
    const key = `rl:${identifier}`;
    const now = Math.floor(Date.now() / 1000);

    const result = await this.redis.eval(RATE_LIMIT_SCRIPT, {
      keys: [key],
      arguments: [
        this.config.maxRequests.toString(),
        this.config.windowSeconds.toString(),
        now.toString(),
      ],
    }) as number[];

    const [allowed, remaining, resetAt, retryAfter] = result;

    return {
      allowed: allowed === 1,
      remaining,
      resetAt,
      retryAfter: retryAfter &amp;gt; 0 ? retryAfter : undefined,
    };
  }
}

function getClientIdentifier(req: IncomingMessage): string {
  const forwarded = req.headers['x-forwarded-for'];
  const ip = Array.isArray(forwarded)
    ? forwarded[0]
    : forwarded?.split(',')[0]?.trim() ?? req.socket.remoteAddress ?? 'unknown';
  return ip;
}

function applyRateLimitHeaders(res: ServerResponse, result: RateLimitResult): void {
  res.setHeader('X-RateLimit-Limit', '100');
  res.setHeader('X-RateLimit-Remaining', result.remaining.toString());
  res.setHeader('X-RateLimit-Reset', result.resetAt.toString());
  if (result.retryAfter !== undefined) {
    res.setHeader('Retry-After', result.retryAfter.toString());
  }
}

async function main(): Promise&amp;lt;void&amp;gt; {
  const redis = createClient({ url: process.env.REDIS_URL });
  await redis.connect();

  const limiter = new RateLimiter(redis, {
    maxRequests: 100,
    windowSeconds: 60,
  });

  const server = createServer(async (req: IncomingMessage, res: ServerResponse) =&amp;gt; {
    const identifier = getClientIdentifier(req);

    try {
      const result = await limiter.check(identifier);
      applyRateLimitHeaders(res, result);

      if (!result.allowed) {
        res.writeHead(429, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          error: 'Too Many Requests',
          retryAfter: result.retryAfter,
        }));
        return;
      }

      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ ok: true }));
    } catch (err) {
      res.writeHead(500);
      res.end('Internal server error');
    }
  });

  server.listen(3000, () =&amp;gt; {
    console.log('Server running on port 3000');
  });
}

main().catch(console.error);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The rate limit logic runs as a Lua script inside Redis via &lt;code&gt;redis.eval&lt;/code&gt;. Redis executes Lua scripts atomically — the entire script runs to completion as a single Redis command. No other Redis command from any other client executes between the &lt;code&gt;GET&lt;/code&gt; and the &lt;code&gt;INCR&lt;/code&gt;. This eliminates the race condition entirely, not just reduces it.&lt;/p&gt;

&lt;p&gt;A Node.js implementation that &lt;code&gt;await redis.get(key)&lt;/code&gt; then checks the count then &lt;code&gt;await redis.incr(key)&lt;/code&gt; has a race window between the get and the incr. Two concurrent requests both see count 99 (one below the limit of 100), both allow the request, both increment to 100 and 101. The script's atomic execution makes that impossible.&lt;/p&gt;

&lt;p&gt;The script returns a four-element array: allowed flag (1 or 0), remaining requests, Unix timestamp of the window reset, and the retry-after value in seconds. The &lt;code&gt;GET&lt;/code&gt; followed by &lt;code&gt;SET ... EX&lt;/code&gt; on a missing key creates the counter with an expiry in one conditional branch. The &lt;code&gt;INCR&lt;/code&gt; on an existing key increments without resetting the expiry, so the window duration is anchored to the first request in the window, not the most recent.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;getClientIdentifier&lt;/code&gt; reads &lt;code&gt;X-Forwarded-For&lt;/code&gt; before falling back to &lt;code&gt;req.socket.remoteAddress&lt;/code&gt;. Behind a load balancer or reverse proxy, &lt;code&gt;remoteAddress&lt;/code&gt; is the proxy's IP address — rate limiting on it throttles all users equally rather than individual clients. &lt;code&gt;X-Forwarded-For&lt;/code&gt; carries the original client IP set by the proxy. Taking the first value from a comma-separated list is correct because proxies append their own IP, so the leftmost value is the original client (assuming you trust your proxy not to be spoofed upstream).&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/node-js-vs-deno-vs-bun/" rel="noopener noreferrer"&gt;Node.js vs Deno vs Bun: Picking the Right JavaScript Runtime in 2026&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Async Error Propagation and the Express Error Handler
&lt;/h2&gt;

&lt;p&gt;Express 4's router does not catch errors thrown from async functions. A thrown error inside an &lt;code&gt;async&lt;/code&gt; route handler that lacks a try/catch hangs the request permanently — the client waits for a response that never comes, and the connection eventually times out.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express, { Request, Response, NextFunction, RequestHandler } from 'express';
import { Pool, DatabaseError } from 'pg';
import { ZodError, z } from 'zod';
import { createLogger } from 'winston';

const logger = createLogger({ level: 'info' });

type AsyncHandler = (req: Request, res: Response, next: NextFunction) =&amp;gt; Promise&amp;lt;void&amp;gt;;

function wrapAsync(fn: AsyncHandler): RequestHandler {
  return (req, res, next) =&amp;gt; {
    fn(req, res, next).catch(next);
  };
}

class AppError extends Error {
  constructor(
    message: string,
    public readonly statusCode: number,
    public readonly code: string,
  ) {
    super(message);
    this.name = 'AppError';
  }
}

const CreateUserSchema = z.object({
  username: z
    .string()
    .min(3)
    .max(30)
    .regex(/^[a-z0-9_-]+$/, 'Username may only contain lowercase letters, numbers, underscores, and hyphens'),
  email: z.string().email(),
  role: z.enum(['member', 'viewer']),
});

interface CreatedUser {
  id: number;
  username: string;
  email: string;
  role: string;
  created_at: Date;
}

function buildRouter(pool: Pool): express.Router {
  const router = express.Router();

  router.post(
    '/users',
    wrapAsync(async (req: Request, res: Response) =&amp;gt; {
      const parsed = CreateUserSchema.safeParse(req.body);

      if (!parsed.success) {
        throw new AppError(
          'Validation failed',
          400,
          'VALIDATION_ERROR',
        );
      }

      const { username, email, role } = parsed.data;

      const existing = await pool.query(
        'SELECT id FROM users WHERE email = $1 OR username = $2 LIMIT 1',
        [email, username],
      );

      if (existing.rowCount &amp;gt; 0) {
        throw new AppError('Username or email already taken', 409, 'CONFLICT');
      }

      const result = await pool.query&amp;lt;CreatedUser&amp;gt;(
        `INSERT INTO users (username, email, role, created_at)
         VALUES ($1, $2, $3, NOW())
         RETURNING id, username, email, role, created_at`,
        [username, email, role],
      );

      res.status(201).json({ user: result.rows[0] });
    }),
  );

  return router;
}

function buildErrorHandler() {
  return (err: unknown, req: Request, res: Response, _next: NextFunction): void =&amp;gt; {
    const requestId = req.headers['x-request-id'] ?? 'unknown';

    if (err instanceof ZodError) {
      logger.warn({ requestId, errors: err.errors }, 'Validation error');
      res.status(400).json({
        error: 'Validation failed',
        code: 'VALIDATION_ERROR',
        details: err.errors,
      });
      return;
    }

    if (err instanceof AppError) {
      logger.warn({ requestId, code: err.code, message: err.message }, 'Application error');
      res.status(err.statusCode).json({
        error: err.message,
        code: err.code,
      });
      return;
    }

    if (err instanceof DatabaseError) {
      if (err.code === '23505') {
        res.status(409).json({ error: 'Conflict', code: 'DUPLICATE_KEY' });
        return;
      }

      if (err.code === '57014') {
        res.status(503).json({ error: 'Database timeout', code: 'DB_TIMEOUT' });
        return;
      }

      logger.error({ requestId, pgCode: err.code, message: err.message }, 'Unhandled database error');
      res.status(500).json({ error: 'Database error', code: 'DB_ERROR' });
      return;
    }

    logger.error({ requestId, err }, 'Unhandled server error');
    res.status(500).json({ error: 'Internal server error', code: 'INTERNAL_ERROR' });
  };
}

function buildApp(pool: Pool): express.Application {
  const app = express();
  app.use(express.json());
  app.use('/api', buildRouter(pool));
  app.use(buildErrorHandler());
  return app;
}

export { buildApp, AppError };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;wrapAsync&lt;/code&gt; is the linchpin. It wraps an async function and returns a standard Express &lt;code&gt;RequestHandler&lt;/code&gt;. If the async function rejects — whether from a thrown &lt;code&gt;AppError&lt;/code&gt;, a database error, a validation error, or any unexpected error — &lt;code&gt;.catch(next)&lt;/code&gt; passes the rejection reason to Express's &lt;code&gt;next&lt;/code&gt; function. Express detects that &lt;code&gt;next&lt;/code&gt; was called with an argument and skips all remaining route handlers, routing directly to error-handling middleware. Error-handling middleware in Express is distinguished by its four-parameter signature &lt;code&gt;(err, req, res, next)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Without &lt;code&gt;wrapAsync&lt;/code&gt;, an async function that throws calls no error handler and sets no response. The socket stays open. &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; does not forcibly close it. Depending on your HTTP client's timeout configuration, the connection hangs for 30–120 seconds before the client gives up. Under load, these hanging connections accumulate, exhaust &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt;'s socket descriptors, and the server stops accepting new connections.&lt;/p&gt;

&lt;p&gt;The error handler inspects the error type in order of specificity. &lt;code&gt;ZodError&lt;/code&gt; means the route handler called &lt;code&gt;safeParse&lt;/code&gt; and threw manually, or a Zod parse ran without &lt;code&gt;safeParse&lt;/code&gt;. &lt;code&gt;AppError&lt;/code&gt; means the application threw a known, typed error with a status code and business code. &lt;code&gt;DatabaseError&lt;/code&gt; from &lt;code&gt;pg&lt;/code&gt; carries PostgreSQL error codes in its &lt;code&gt;code&lt;/code&gt; property — &lt;code&gt;23505&lt;/code&gt; is &lt;code&gt;unique_violation&lt;/code&gt; (a duplicate key constraint), &lt;code&gt;57014&lt;/code&gt; is &lt;code&gt;query_canceled&lt;/code&gt; (statement timeout hit). Anything else is an unknown error that warrants a 500 and a high-severity log entry.&lt;/p&gt;

&lt;p&gt;Checking &lt;code&gt;existing.rowCount&lt;/code&gt; before the insert is application-level duplicate detection. It is not a replacement for the database constraint — the database constraint enforces uniqueness even if two requests pass the application check simultaneously. The application check provides a clear error message. The database constraint catches the race. Both are necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Graceful Shutdown: Draining the Event Loop
&lt;/h2&gt;

&lt;p&gt;When a &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; process receives &lt;code&gt;SIGTERM&lt;/code&gt; — from Kubernetes scaling down a pod, a deploy restart, or an operator signal — you have two options. You can call &lt;code&gt;process.exit(0)&lt;/code&gt; immediately and drop every in-flight request. Or you can stop accepting new connections, wait for in-flight requests to complete, close database connections cleanly, and then exit.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createServer, Server } from 'http';
import { Pool } from 'pg';
import { createClient } from 'redis';
import { createLogger } from 'winston';

const logger = createLogger({ level: 'info' });

interface ShutdownConfig {
  gracePeriodMs: number;
  hardKillMs: number;
}

class GracefulShutdown {
  private readonly server: Server;
  private readonly pool: Pool;
  private readonly redis: ReturnType&amp;lt;typeof createClient&amp;gt;;
  private readonly config: ShutdownConfig;
  private isShuttingDown = false;
  private activeConnections = new Set&amp;lt;import('net').Socket&amp;gt;();

  constructor(
    server: Server,
    pool: Pool,
    redis: ReturnType&amp;lt;typeof createClient&amp;gt;,
    config: ShutdownConfig,
  ) {
    this.server = server;
    this.pool = pool;
    this.redis = redis;
    this.config = config;

    this.server.on('connection', (socket) =&amp;gt; {
      this.activeConnections.add(socket);
      socket.once('close', () =&amp;gt; this.activeConnections.delete(socket));
    });
  }

  register(): void {
    process.once('SIGTERM', () =&amp;gt; this.shutdown('SIGTERM'));
    process.once('SIGINT', () =&amp;gt; this.shutdown('SIGINT'));
    process.once('unhandledRejection', (reason) =&amp;gt; {
      logger.fatal({ reason }, 'Unhandled promise rejection — initiating shutdown');
      this.shutdown('unhandledRejection');
    });
  }

  private async shutdown(signal: string): Promise&amp;lt;void&amp;gt; {
    if (this.isShuttingDown) return;
    this.isShuttingDown = true;

    logger.info({ signal }, 'Shutdown signal received — draining');

    const hardKillTimer = setTimeout(() =&amp;gt; {
      logger.fatal('Graceful shutdown timed out — forcing exit');
      process.exit(1);
    }, this.config.hardKillMs);

    hardKillTimer.unref();

    await new Promise&amp;lt;void&amp;gt;((resolve) =&amp;gt; {
      this.server.close((err) =&amp;gt; {
        if (err) logger.error({ err }, 'Error closing HTTP server');
        resolve();
      });
    });

    logger.info(
      { activeConnections: this.activeConnections.size },
      'HTTP server closed — waiting for active connections',
    );

    const graceDeadline = Date.now() + this.config.gracePeriodMs;

    await new Promise&amp;lt;void&amp;gt;((resolve) =&amp;gt; {
      const interval = setInterval(() =&amp;gt; {
        if (this.activeConnections.size === 0 || Date.now() &amp;gt;= graceDeadline) {
          clearInterval(interval);
          for (const socket of this.activeConnections) {
            socket.destroy();
          }
          resolve();
        }
      }, 100);
    });

    logger.info('Active connections drained — closing dependencies');

    await Promise.allSettled([
      this.pool.end(),
      this.redis.quit(),
    ]);

    logger.info('Shutdown complete');
    process.exit(0);
  }
}

async function startServer(): Promise&amp;lt;void&amp;gt; {
  const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 20,
  });

  const redis = createClient({ url: process.env.REDIS_URL });
  await redis.connect();

  const app = buildApp(pool);
  const server = createServer(app);

  const shutdown = new GracefulShutdown(server, pool, redis, {
    gracePeriodMs: 10_000,
    hardKillMs: 30_000,
  });

  shutdown.register();

  server.listen(3000, () =&amp;gt; {
    logger.info('Server listening on port 3000');
  });
}

startServer().catch((err) =&amp;gt; {
  console.error('Startup failed:', err);
  process.exit(1);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;server.close()&lt;/code&gt; stops the HTTP server from accepting new connections. Connections already established remain open. An HTTP keep-alive connection sitting idle between requests counts as an active connection. The polling loop every 100ms checks whether active connections have dropped to zero or whether the grace period has expired. Sockets that persist past the grace period get destroyed with &lt;code&gt;socket.destroy()&lt;/code&gt;, which closes them without waiting for a graceful TCP close.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;hardKillTimer.unref()&lt;/code&gt; is essential. Without it, the &lt;code&gt;setTimeout&lt;/code&gt; holding the hard kill timer keeps the &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; event loop alive even after all other work is done. &lt;code&gt;unref()&lt;/code&gt; tells &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; not to count this timer when deciding whether to exit naturally. The timer still fires if the process is still running when it expires; it just does not prevent the process from exiting before then.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Promise.allSettled&lt;/code&gt; on the pool end and Redis quit means both connections attempt to close regardless of whether one throws. Using &lt;code&gt;Promise.all&lt;/code&gt; would mean a Redis disconnect error prevents the database pool from closing, leaving pooled connections open against the database after the process exits. The database then waits for those connections to time out before releasing their resources.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;unhandledRejection&lt;/code&gt; handler triggers the same shutdown path as &lt;code&gt;SIGTERM&lt;/code&gt;. An unhandled rejection means the application reached a state it did not anticipate. Continuing to serve requests from a process in an unknown state is worse than restarting cleanly. Kubernetes or whatever process manager you use will restart the pod; graceful shutdown gives in-flight requests time to complete first.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Mental Model
&lt;/h2&gt;

&lt;p&gt;The event loop operates on a priority hierarchy. Synchronous &lt;a href="https://sudosecurity.org/what-is-javascript/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; on the call stack runs first. When the stack empties, all queued microtasks drain — every pending Promise continuation, every &lt;code&gt;queueMicrotask&lt;/code&gt; callback, every queued microtask added by those microtasks. Only after the microtask queue is completely empty does the event loop pull one &lt;code&gt;macrotask&lt;/code&gt; from the task queue (a &lt;code&gt;setTimeout&lt;/code&gt;, a &lt;code&gt;setInterval&lt;/code&gt;, an &lt;code&gt;I/O&lt;/code&gt; callback) and push it onto the call stack. Then the cycle repeats: run the stack, drain microtasks, pull one &lt;code&gt;macrotask&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This ordering has concrete consequences for every async pattern in production code. Database query responses resume as microtasks. Timer callbacks fire as &lt;code&gt;macrotasks&lt;/code&gt;. Deferring a state mutation to a &lt;code&gt;macrotask&lt;/code&gt; with &lt;code&gt;setTimeout(..., 0)&lt;/code&gt; instead of awaiting it directly creates a window where concurrent microtasks read stale state. Atomic operations in Redis or PostgreSQL close that window by moving the mutual exclusion into the database layer, where it belongs.&lt;/p&gt;

&lt;p&gt;The event loop is not an abstraction over multi-threading. It is a single thread coordinating &lt;code&gt;I/O&lt;/code&gt; through non-blocking OS calls and a priority-ordered queue system. Understanding which queue your callback lands in, and when that queue drains, tells you exactly when your code runs relative to everything else in the process. That knowledge is what separates code that works on a developer's machine from code that holds up under production load.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Building a Modern App With React, Vite, and Tailwind CSS: The Complete 2025 Guide</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Thu, 26 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/building-a-modern-app-with-react-vite-and-tailwind-css-the-complete-2025-guide-21c8</link>
      <guid>https://dev.to/sudosecurity/building-a-modern-app-with-react-vite-and-tailwind-css-the-complete-2025-guide-21c8</guid>
      <description>&lt;p&gt;Liquid syntax error: Variable '{{% raw %}' was not properly terminated with regexp: /\}\}/&lt;/p&gt;
</description>
      <category>react</category>
      <category>tailwindcss</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Node.js vs Deno vs Bun: Picking the Right JavaScript Runtime in 2026</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Wed, 25 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/nodejs-vs-deno-vs-bun-picking-the-right-javascript-runtime-in-2026-4h5c</link>
      <guid>https://dev.to/sudosecurity/nodejs-vs-deno-vs-bun-picking-the-right-javascript-runtime-in-2026-4h5c</guid>
      <description>&lt;p&gt;In 2009, there was one JavaScript runtime outside the browser. In 2026, there are three mainstream options, each built by people who looked at Node.js and thought they could do it better. Two of them were built by people who worked on Node.&lt;/p&gt;

&lt;p&gt;This isn't a horse race with a single winner. Node.js, Deno, and Bun make different tradeoffs, serve different priorities, and genuinely excel in different contexts. The question isn't which one won. It's which one fits your situation.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Quick Overview
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Node.js&lt;/strong&gt; is the established runtime. 15+ years old, &lt;code&gt;npm&lt;/code&gt; ecosystem with two million packages, production-proven at massive scale, and the baseline everything else is measured against.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deno&lt;/strong&gt; is Ryan Dahl's redesign of Node.js. Built in Rust, runs TypeScript natively, has a security-first permission model, uses web-standard APIs, and ships with a complete toolchain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bun&lt;/strong&gt; is a performance-focused reimplementation of the Node.js API surface. Written in Zig, uses &lt;code&gt;JavaScriptCore&lt;/code&gt; instead of V8, runs TypeScript natively, includes a package manager that's dramatically faster than &lt;code&gt;npm&lt;/code&gt;, and aims for drop-in Node.js compatibility.&lt;/p&gt;

&lt;h2&gt;
  
  
  Comparison: The Key Dimensions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Engine
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Runtime&lt;/th&gt;
&lt;th&gt;Engine&lt;/th&gt;
&lt;th&gt;Language&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Node.js&lt;/td&gt;
&lt;td&gt;V8 (Chrome)&lt;/td&gt;
&lt;td&gt;C++&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Deno&lt;/td&gt;
&lt;td&gt;V8 (Chrome)&lt;/td&gt;
&lt;td&gt;Rust&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bun&lt;/td&gt;
&lt;td&gt;JavaScriptCore (Safari/WebKit)&lt;/td&gt;
&lt;td&gt;Zig&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Node and Deno share V8. Bun uses JavaScriptCore. For most workloads, the engine choice matters less than people think. V8 has an extraordinarily mature JIT compiler. JavaScriptCore is competitive but optimized differently.&lt;/p&gt;

&lt;h3&gt;
  
  
  TypeScript Support
&lt;/h3&gt;

&lt;p&gt;Node.js does not run TypeScript natively. You need &lt;code&gt;tsc&lt;/code&gt;, &lt;code&gt;tsx&lt;/code&gt;, &lt;code&gt;esbuild&lt;/code&gt;, or a bundler. Node 23+ has experimental &lt;code&gt;--experimental-strip-types&lt;/code&gt; support for running TypeScript files, but it's not production-ready and it doesn't support all TypeScript features.&lt;/p&gt;

&lt;p&gt;Deno and Bun both run TypeScript natively. &lt;code&gt;deno run app.ts&lt;/code&gt; and &lt;code&gt;bun app.ts&lt;/code&gt; work without any setup.&lt;/p&gt;

&lt;p&gt;For teams that use TypeScript (which should be most teams, per &lt;a href="https://sudosecurity.org/javascript-vs-typescript/" rel="noopener noreferrer"&gt;JavaScript vs TypeScript&lt;/a&gt;), Deno and Bun eliminate an entire category of toolchain friction.&lt;/p&gt;

&lt;h3&gt;
  
  
  Package Management
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Node.js / npm:&lt;/strong&gt; The baseline. Reads &lt;code&gt;package.json&lt;/code&gt;, installs to &lt;code&gt;node_modules&lt;/code&gt;, writes &lt;code&gt;package-lock.json&lt;/code&gt;. Works with every package ever. Slow on large dependency trees. &lt;code&gt;node_modules&lt;/code&gt; can reach hundreds of megabytes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deno:&lt;/strong&gt; Imports from URLs or with &lt;code&gt;npm:&lt;/code&gt; and &lt;code&gt;jsr:&lt;/code&gt; prefixes. No &lt;code&gt;node_modules&lt;/code&gt; directory. Packages cache globally. First install downloads from the internet; subsequent runs use cache. The &lt;code&gt;deno.json&lt;/code&gt; import map pins versions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bun:&lt;/strong&gt; npm-compatible. Reads &lt;code&gt;package.json&lt;/code&gt;, installs to &lt;code&gt;node_modules&lt;/code&gt;, writes &lt;code&gt;bun.lockb&lt;/code&gt; (binary lockfile). Much faster than npm due to parallel downloads, hardlink caching, and optimized I/O. Installing 500 packages that npm takes 45 seconds on, Bun handles in under 5.&lt;/p&gt;

&lt;p&gt;If you're running CI pipelines and package installation is on the critical path, Bun's package manager alone is worth evaluating.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/what-is-deno/" rel="noopener noreferrer"&gt;What is Deno? Ryan Dahl's Second Attempt at a JavaScript Runtime&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  Security Model
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Node.js:&lt;/strong&gt; No restrictions. Any script can read files, make network requests, execute subprocesses, and access environment variables. You trust every package you install.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deno:&lt;/strong&gt; Permission flags are required. &lt;code&gt;--allow-read&lt;/code&gt;, &lt;code&gt;--allow-net&lt;/code&gt;, &lt;code&gt;--allow-env&lt;/code&gt;, &lt;code&gt;--allow-run&lt;/code&gt;. Permissions can be scoped: &lt;code&gt;--allow-net=api.example.com&lt;/code&gt; restricts outbound connections to that host. Running without permissions fails immediately with an actionable error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bun:&lt;/strong&gt; No restrictions. Same model as Node.js.&lt;/p&gt;

&lt;p&gt;The security difference is material. In the Node/Bun model, a compromised dependency has access to everything your process has access to. In Deno, a compromised dependency can only do what the permission flags allow.&lt;/p&gt;

&lt;p&gt;Supply chain attacks in the JavaScript ecosystem have happened. The &lt;a href="https://sudosecurity.org/your-https-is-toast/" rel="noopener noreferrer"&gt;HTTPS article&lt;/a&gt; covers the broader context of why trust models in software matter. Deno's permission system is a meaningful mitigation, not a complete solution.&lt;/p&gt;

&lt;h3&gt;
  
  
  Built-in Tooling
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Tool&lt;/th&gt;
&lt;th&gt;Node.js&lt;/th&gt;
&lt;th&gt;Deno&lt;/th&gt;
&lt;th&gt;Bun&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;TypeScript execution&lt;/td&gt;
&lt;td&gt;No (via tsx/tsc)&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Formatter&lt;/td&gt;
&lt;td&gt;No (Prettier)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;deno fmt&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;No (Prettier)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Linter&lt;/td&gt;
&lt;td&gt;No (ESLint)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;deno lint&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;No (ESLint)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Test runner&lt;/td&gt;
&lt;td&gt;No (Jest/Vitest)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;deno test&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;bun test&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bundler&lt;/td&gt;
&lt;td&gt;No (Webpack/esbuild)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;deno bundle&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;bun build&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Package manager&lt;/td&gt;
&lt;td&gt;npm&lt;/td&gt;
&lt;td&gt;URL imports / npm:&lt;/td&gt;
&lt;td&gt;&lt;code&gt;bun install&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Watch mode&lt;/td&gt;
&lt;td&gt;No (&lt;code&gt;nodemon&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;--watch&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;--watch&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Deno wins on toolchain completeness. You install Deno and have everything you need for a new project without making any package choices. Bun covers the most important pieces (test runner, bundler, package manager). Node.js requires assembling the toolchain yourself.&lt;/p&gt;

&lt;p&gt;The Node.js toolchain argument: npm's 15 years of development means those external tools are mature, well-documented, and heavily supported. &lt;code&gt;deno fmt&lt;/code&gt; and &lt;code&gt;bun test&lt;/code&gt; are new. Your team might have strong opinions about Prettier's formatting rules. ESLint has hundreds of community plugins.&lt;/p&gt;

&lt;h3&gt;
  
  
  Web Standard API Support
&lt;/h3&gt;

&lt;p&gt;Deno was built to use browser APIs. &lt;code&gt;fetch&lt;/code&gt;, &lt;code&gt;Request&lt;/code&gt;, &lt;code&gt;Response&lt;/code&gt;, &lt;code&gt;URL&lt;/code&gt;, &lt;code&gt;ReadableStream&lt;/code&gt;, &lt;code&gt;TextEncoder&lt;/code&gt;, &lt;code&gt;Crypto&lt;/code&gt; — these work in Deno the same way they work in a browser.&lt;/p&gt;

&lt;p&gt;Bun follows the same philosophy. &lt;code&gt;fetch&lt;/code&gt; is built in. Web standard APIs work.&lt;/p&gt;

&lt;p&gt;Node.js added &lt;code&gt;fetch&lt;/code&gt; in Node 18, and has been back-filling web standard APIs since. The coverage is good but not complete, and some Node APIs are older, with different signatures than their browser equivalents.&lt;/p&gt;

&lt;p&gt;For code that you want to run on both a server and at the edge (Cloudflare Workers, Deno Deploy, Fastly Compute), web standard API compatibility matters. Code written against &lt;code&gt;fetch&lt;/code&gt; and &lt;code&gt;Response&lt;/code&gt; runs everywhere. Code written against Node's &lt;code&gt;http&lt;/code&gt; module runs only in Node.&lt;/p&gt;

&lt;h3&gt;
  
  
  Performance
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Startup time:&lt;/strong&gt; Bun starts fastest. Relevant for scripts, CLI tools, and serverless functions with cold starts. Less relevant for long-running servers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HTTP throughput:&lt;/strong&gt; Benchmarks vary by workload. For raw hello-world HTTP serving, Bun is typically fastest, Deno second, Node third. For real application workloads with database queries, the gap narrows. The bottleneck shifts to the database, not the runtime.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Package installation:&lt;/strong&gt; Bun is dramatically faster than npm. 3-10x depending on the project. This matters daily for local development and significantly for CI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Memory footprint:&lt;/strong&gt; Node.js and Deno (both V8) use more memory at idle than Bun. For memory-constrained environments (small VPS, containers), this matters.&lt;/p&gt;

&lt;p&gt;Don't pick a runtime based on synthetic benchmarks. Pick based on what your team needs to ship and maintain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Module System
&lt;/h2&gt;

&lt;p&gt;All three runtimes support ES Modules (&lt;code&gt;import&lt;/code&gt;/&lt;code&gt;export&lt;/code&gt;). Node.js also supports CommonJS (&lt;code&gt;require()&lt;/code&gt;). Deno supports only ES Modules natively, plus &lt;code&gt;npm:&lt;/code&gt; and &lt;code&gt;jsr:&lt;/code&gt; imports that wrap CommonJS packages transparently. Bun supports both.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// CommonJS (Node.js and Bun)
const express = require("express");

// ES Modules (all three)
import express from "express";

// Deno import (URL-based)
import { serve } from "https://deno.land/std@0.220.0/http/server.ts";

// npm: prefix (Deno and Bun)
import express from "npm:express";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you're writing a library intended to run on all three runtimes, write ES Modules.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ecosystem Maturity
&lt;/h2&gt;

&lt;p&gt;Node.js has the mature ecosystem. Two million npm packages. Every major database has a Node driver. Every cloud provider has a Node SDK. When you need a library for something unusual, it exists.&lt;/p&gt;

&lt;p&gt;Bun's npm compatibility means it inherits most of this. The exceptions are packages with native Node addons compiled with &lt;code&gt;node-gyp&lt;/code&gt; — those don't work in Bun. Most packages don't use native addons.&lt;/p&gt;

&lt;p&gt;Deno's npm compatibility (via &lt;code&gt;npm:&lt;/code&gt; prefix) is good and improving. Packages that rely on Node-specific internals may not work. The JSR registry is growing with TypeScript-first packages that work across runtimes.&lt;/p&gt;

&lt;p&gt;For production backend work that relies on a specific stack (database drivers, authentication libraries, observability tools), Node's ecosystem is the safe choice. For greenfield projects or edge functions, Deno and Bun have enough to work with.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/what-is-bun/" rel="noopener noreferrer"&gt;What is Bun? The JavaScript Runtime That Made npm Install Fast&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Making the Decision
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Node.js when:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your team knows it and it's working&lt;/li&gt;
&lt;li&gt;You have existing Node codebases to maintain&lt;/li&gt;
&lt;li&gt;You need specific packages that don't work on Bun or Deno&lt;/li&gt;
&lt;li&gt;Stability and ecosystem depth matter more than developer experience improvements&lt;/li&gt;
&lt;li&gt;You're building something where production track record is the primary concern&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Deno when:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Security permissions are a genuine requirement (scripts that handle sensitive data, scripts you run on behalf of others)&lt;/li&gt;
&lt;li&gt;You want a complete, opinionated toolchain without configuration&lt;/li&gt;
&lt;li&gt;You're targeting edge compute (Deno Deploy, Cloudflare Workers has a Deno-compatible layer)&lt;/li&gt;
&lt;li&gt;You want the web standard API model throughout&lt;/li&gt;
&lt;li&gt;Your team will benefit from TypeScript-native execution&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Bun when:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Development speed and toolchain simplicity are the priority&lt;/li&gt;
&lt;li&gt;You want Node.js compatibility with faster startup and faster package installation&lt;/li&gt;
&lt;li&gt;You're building CLI tools where startup time matters&lt;/li&gt;
&lt;li&gt;You want built-in SQLite without a dependency&lt;/li&gt;
&lt;li&gt;Your CI pipeline's package installation is slow and you want an easy win&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Bun as a development tool, Node in production when:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your production infrastructure is Node.js and you want to keep it there&lt;/li&gt;
&lt;li&gt;You want faster &lt;code&gt;bun install&lt;/code&gt; and &lt;code&gt;bun test&lt;/code&gt; without changing the production runtime&lt;/li&gt;
&lt;li&gt;You're not ready to fully migrate but want the day-to-day improvements&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Migration Question
&lt;/h2&gt;

&lt;p&gt;Going from Node to Bun is the easiest migration. For many projects, it's: install Bun, run &lt;code&gt;bun install&lt;/code&gt;, run &lt;code&gt;bun run start&lt;/code&gt;. If all your dependencies have npm packages without native addons, it often works immediately.&lt;/p&gt;

&lt;p&gt;Going from Node to Deno requires more work. Deno 2.0's npm support helps considerably, but code using CommonJS, Node-specific file system APIs, and certain middleware patterns needs updating. The security permission model also requires adding &lt;code&gt;--allow-*&lt;/code&gt; flags to every script.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Longer View
&lt;/h2&gt;

&lt;p&gt;Node.js isn't going anywhere. Companies built their infrastructure on it. The ecosystem is too large. What's likely is that Bun takes development tooling market share (because faster is better and the compatibility story is good), Deno takes edge compute and security-sensitive scripting (because the permission model and Deno Deploy are genuinely compelling), and Node.js maintains its position in production backend work.&lt;/p&gt;

&lt;p&gt;All three are worth knowing. The &lt;a href="https://sudosecurity.org/deep-dive-deno-bun/" rel="noopener noreferrer"&gt;deep dive on Deno and Bun&lt;/a&gt; covers what both runtimes look like when you build something real with them.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Writing Your Own API From Scratch in TypeScript</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Tue, 24 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/writing-your-own-api-from-scratch-in-typescript-4lbn</link>
      <guid>https://dev.to/sudosecurity/writing-your-own-api-from-scratch-in-typescript-4lbn</guid>
      <description>&lt;p&gt;Every tutorial on building a Node.js API shows you something like this: twenty lines of Express, a couple of route handlers, and a &lt;code&gt;res.json({ message: 'hello' })&lt;/code&gt;. The tutorial calls that a REST API. It is technically true. It is also completely useless as a reference for building anything you would actually deploy.&lt;/p&gt;

&lt;p&gt;Production APIs need authentication, input validation, meaningful error handling, database connection pooling, structured logging, rate limiting, and tests. They need configuration management that does not involve hardcoding secrets. They need graceful shutdown so in-flight requests complete when the server stops. They need documentation.&lt;/p&gt;

&lt;p&gt;This article builds a real API from scratch. &lt;a href="https://sudosecurity.org/javascript-vs-typescript/" rel="noopener noreferrer"&gt;TypeScript&lt;/a&gt; throughout. Every piece that actually matters in production. No shortcuts dressed up as simplicity.&lt;/p&gt;

&lt;p&gt;If you want to understand what the code is doing conceptually before writing it, start with &lt;a href="https://sudosecurity.org/what-is-an-api/" rel="noopener noreferrer"&gt;What is an API&lt;/a&gt;. If you want to understand the database layer, read &lt;a href="https://sudosecurity.org/what-is-a-database/" rel="noopener noreferrer"&gt;What is a Database&lt;/a&gt;. This article assumes you know &lt;a href="https://sudosecurity.org/what-is-node-js/" rel="noopener noreferrer"&gt;JavaScript&lt;/a&gt; and have at least read about TypeScript.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Setup
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir my-api &amp;amp;&amp;amp; cd my-api
npm init -y

npm install express pg bcryptjs jsonwebtoken zod express-rate-limit helmet cors morgan uuid
npm install --save-dev typescript @types/express @types/pg @types/bcryptjs @types/jsonwebtoken @types/morgan @types/cors @types/uuid ts-node-dev jest @types/jest ts-jest supertest @types/supertest

npx tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;tsconfig.json&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "compilerOptions": {
        "target": "ES2022",
        "lib": ["ES2022"],
        "module": "commonjs",
        "moduleResolution": "node",
        "rootDir": "./src",
        "outDir": "./dist",
        "strict": true,
        "noUncheckedIndexedAccess": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "exactOptionalPropertyTypes": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "resolveJsonModule": true,
        "declaration": true,
        "declarationMap": true,
        "sourceMap": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist", "**/*.test.ts"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;package.json&lt;/code&gt; scripts:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "scripts": {
        "dev": "ts-node-dev --respawn --transpile-only src/index.ts",
        "build": "tsc",
        "start": "node dist/index.js",
        "test": "jest --coverage",
        "test:watch": "jest --watch",
        "migrate": "ts-node src/database/migrate.ts"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Project structure:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/
    config/
        index.ts
    database/
        index.ts
        migrate.ts
    middleware/
        auth.ts
        errorHandler.ts
        validate.ts
        rateLimiter.ts
        requestLogger.ts
    routes/
        auth.ts
        products.ts
        orders.ts
        index.ts
    types/
        index.ts
        express.d.ts
    utils/
        logger.ts
        errors.ts
        jwt.ts
    app.ts
    index.ts
tests/
    auth.test.ts
    products.test.ts
    setup.ts
.env
.env.test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { z } from 'zod';
import dotenv from 'dotenv';

dotenv.config();

const envSchema = z.object({
    NODE_ENV:           z.enum(['development', 'test', 'production']).default('development'),
    PORT:               z.coerce.number().int().positive().default(3000),
    DATABASE_URL:       z.string().url(),
    JWT_ACCESS_SECRET:  z.string().min(32),
    JWT_REFRESH_SECRET: z.string().min(32),
    JWT_ACCESS_EXPIRES: z.string().default('15m'),
    JWT_REFRESH_EXPIRES: z.string().default('30d'),
    BCRYPT_ROUNDS:      z.coerce.number().int().min(10).default(12),
    RATE_LIMIT_WINDOW:  z.coerce.number().int().positive().default(60000),
    RATE_LIMIT_MAX:     z.coerce.number().int().positive().default(100),
    CORS_ORIGINS:       z.string().default('http://localhost:3000'),
    LOG_LEVEL:          z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

const parsed = envSchema.safeParse(process.env);

if (!parsed.success) {
    console.error('Invalid environment variables:');
    for (const issue of parsed.error.issues) {
        console.error(`  ${issue.path.join('.')}: ${issue.message}`);
    }
    process.exit(1);
}

export const config = parsed.data;
export type Config = typeof config;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Validating environment variables at startup is a pattern that prevents a whole class of production incidents. The server does not start with a missing &lt;code&gt;DATABASE_URL&lt;/code&gt;. It fails immediately with a clear error message rather than running for an hour before the first database query fails. Zod validates and coerces types: &lt;code&gt;PORT&lt;/code&gt; comes in as a string from &lt;code&gt;process.env&lt;/code&gt; but is coerced to a number.&lt;/p&gt;

&lt;h2&gt;
  
  
  Structured Logging
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { config } from '../config';

type LogLevel = 'debug' | 'info' | 'warn' | 'error';
type LogContext = Record&amp;lt;string, unknown&amp;gt;;

const levels: Record&amp;lt;LogLevel, number&amp;gt; = {
    debug: 0, info: 1, warn: 2, error: 3
};

function shouldLog(level: LogLevel): boolean {
    return levels[level] &amp;gt;= levels[config.LOG_LEVEL];
}

function formatLog(level: LogLevel, message: string, context?: LogContext): string {
    const entry = {
        timestamp: new Date().toISOString(),
        level,
        message,
        ...(context &amp;amp;&amp;amp; Object.keys(context).length &amp;gt; 0 ? { context } : {}),
        pid: process.pid,
        env: config.NODE_ENV,
    };
    return JSON.stringify(entry);
}

export const logger = {
    debug: (message: string, context?: LogContext) =&amp;gt; {
        if (shouldLog('debug')) process.stdout.write(formatLog('debug', message, context) + '\n');
    },
    info: (message: string, context?: LogContext) =&amp;gt; {
        if (shouldLog('info')) process.stdout.write(formatLog('info', message, context) + '\n');
    },
    warn: (message: string, context?: LogContext) =&amp;gt; {
        if (shouldLog('warn')) process.stderr.write(formatLog('warn', message, context) + '\n');
    },
    error: (message: string, context?: LogContext) =&amp;gt; {
        if (shouldLog('error')) process.stderr.write(formatLog('error', message, context) + '\n');
    },
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Structured JSON logs are the standard for production systems. Every log entry is a JSON object with consistent fields. Log aggregation systems (Datadog, CloudWatch, ELK stack) parse JSON natively. You can query "all error logs where &lt;code&gt;context.user_id = 123&lt;/code&gt;" in seconds. Unstructured text logs require regex to extract fields and break whenever the message format changes.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/js-event-loop-deep-dive/" rel="noopener noreferrer"&gt;The JavaScript Event Loop: Call Stack, Task Queue &amp;amp; Microtasks&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Custom Errors
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class AppError extends Error {
    constructor(
        public readonly statusCode: number,
        public readonly code: string,
        message: string,
        public readonly details?: unknown
    ) {
        super(message);
        this.name = 'AppError';
        Object.setPrototypeOf(this, AppError.prototype);
    }
}

export class NotFoundError extends AppError {
    constructor(resource: string, id?: string | number) {
        super(
            404,
            'NOT_FOUND',
            id ? `${resource} with ID ${id} not found` : `${resource} not found`
        );
    }
}

export class ValidationError extends AppError {
    constructor(details: Array&amp;lt;{ field: string; message: string }&amp;gt;) {
        super(400, 'VALIDATION_ERROR', 'Request validation failed', details);
    }
}

export class UnauthorizedError extends AppError {
    constructor(message = 'Authentication required') {
        super(401, 'UNAUTHORIZED', message);
    }
}

export class ForbiddenError extends AppError {
    constructor(message = 'Insufficient permissions') {
        super(403, 'FORBIDDEN', message);
    }
}

export class ConflictError extends AppError {
    constructor(message: string) {
        super(409, 'CONFLICT', message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Custom error classes let you throw semantically meaningful errors anywhere in your application and handle them uniformly in one place. &lt;code&gt;throw new NotFoundError('Product', slug)&lt;/code&gt; from inside a repository function carries everything the error handler needs to produce the right HTTP response. No error code hunting. No &lt;code&gt;if (err.code === 'some_string')&lt;/code&gt; scattered through route handlers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Layer
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Pool, PoolClient } from 'pg';
import { config } from '../config';
import { logger } from '../utils/logger';

const pool = new Pool({
    connectionString:          config.DATABASE_URL,
    max:                       20,
    idleTimeoutMillis:         30000,
    connectionTimeoutMillis:   2000,
    statement_timeout:         30000,
    query_timeout:             30000,
    application_name:          'my-api',
});

pool.on('error', (err) =&amp;gt; {
    logger.error('Unexpected error on idle database client', { error: err.message });
});

pool.on('connect', () =&amp;gt; {
    logger.debug('New database connection established');
});

export async function query&amp;lt;T extends Record&amp;lt;string, unknown&amp;gt; = Record&amp;lt;string, unknown&amp;gt;&amp;gt;(
    text: string,
    params?: unknown[]
): Promise&amp;lt;T[]&amp;gt; {
    const start = Date.now();
    try {
        const result = await pool.query&amp;lt;T&amp;gt;(text, params);
        const duration = Date.now() - start;
        if (duration &amp;gt; 1000) {
            logger.warn('Slow query detected', { duration, query: text.substring(0, 100) });
        }
        return result.rows;
    } catch (err) {
        logger.error('Database query error', {
            error: (err as Error).message,
            query: text.substring(0, 100),
        });
        throw err;
    }
}

export async function queryOne&amp;lt;T extends Record&amp;lt;string, unknown&amp;gt; = Record&amp;lt;string, unknown&amp;gt;&amp;gt;(
    text: string,
    params?: unknown[]
): Promise&amp;lt;T | null&amp;gt; {
    const rows = await query&amp;lt;T&amp;gt;(text, params);
    return rows[0] ?? null;
}

export async function transaction&amp;lt;T&amp;gt;(
    callback: (client: PoolClient) =&amp;gt; Promise&amp;lt;T&amp;gt;
): Promise&amp;lt;T&amp;gt; {
    const client = await pool.connect();
    try {
        await client.query('BEGIN');
        const result = await callback(client);
        await client.query('COMMIT');
        return result;
    } catch (err) {
        await client.query('ROLLBACK');
        throw err;
    } finally {
        client.release();
    }
}

export async function closePool(): Promise&amp;lt;void&amp;gt; {
    await pool.end();
    logger.info('Database pool closed');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;transaction&lt;/code&gt; helper wraps the &lt;code&gt;BEGIN&lt;/code&gt; / &lt;code&gt;COMMIT&lt;/code&gt; / &lt;code&gt;ROLLBACK&lt;/code&gt; pattern that you need for any multi-step database operation. Pass a callback, do your work inside it, and the helper handles the lifecycle. If the callback throws, the transaction rolls back. If it succeeds, it commits. &lt;code&gt;client.release()&lt;/code&gt; in the &lt;code&gt;finally&lt;/code&gt; block returns the connection to the pool regardless of outcome.&lt;/p&gt;

&lt;p&gt;Slow query logging in &lt;code&gt;query()&lt;/code&gt; surfaces performance problems without requiring additional instrumentation. Any query taking more than one second writes a warning log with the query text and duration. This is how you find missing indexes in production before they cause outages.&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Migrations
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { query, closePool } from './index';
import { logger } from '../utils/logger';

const migrations = [
    {
        version: 1,
        name: 'create_users',
        sql: `
            CREATE TABLE IF NOT EXISTS users (
                id           BIGSERIAL PRIMARY KEY,
                username     VARCHAR(80)  NOT NULL UNIQUE,
                email        VARCHAR(255) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                is_active    BOOLEAN      NOT NULL DEFAULT true,
                is_admin     BOOLEAN      NOT NULL DEFAULT false,
                last_login   TIMESTAMPTZ,
                created_at   TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
                updated_at   TIMESTAMPTZ  NOT NULL DEFAULT NOW()
            );
            CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
            CREATE INDEX IF NOT EXISTS idx_users_created ON users(created_at);
        `,
    },
    {
        version: 2,
        name: 'create_refresh_tokens',
        sql: `
            CREATE TABLE IF NOT EXISTS refresh_tokens (
                id         BIGSERIAL PRIMARY KEY,
                user_id    BIGINT      NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                token_hash VARCHAR(255) NOT NULL UNIQUE,
                expires_at TIMESTAMPTZ  NOT NULL,
                revoked    BOOLEAN      NOT NULL DEFAULT false,
                created_at TIMESTAMPTZ  NOT NULL DEFAULT NOW()
            );
            CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens(user_id);
            CREATE INDEX IF NOT EXISTS idx_refresh_tokens_hash ON refresh_tokens(token_hash);
        `,
    },
    {
        version: 3,
        name: 'create_categories_and_products',
        sql: `
            CREATE TABLE IF NOT EXISTS categories (
                id          SERIAL PRIMARY KEY,
                name        VARCHAR(100) NOT NULL UNIQUE,
                slug        VARCHAR(100) NOT NULL UNIQUE,
                description TEXT,
                parent_id   INTEGER REFERENCES categories(id) ON DELETE SET NULL,
                created_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW()
            );

            CREATE TABLE IF NOT EXISTS products (
                id          BIGSERIAL PRIMARY KEY,
                name        VARCHAR(255) NOT NULL,
                slug        VARCHAR(255) NOT NULL UNIQUE,
                description TEXT         NOT NULL,
                price       NUMERIC(10,2) NOT NULL CHECK (price &amp;gt; 0),
                stock       INTEGER       NOT NULL DEFAULT 0 CHECK (stock &amp;gt;= 0),
                category_id INTEGER       NOT NULL REFERENCES categories(id) ON DELETE RESTRICT,
                owner_id    BIGINT        NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                status      VARCHAR(20)   NOT NULL DEFAULT 'draft'
                                          CHECK (status IN ('draft','active','archived')),
                created_at  TIMESTAMPTZ   NOT NULL DEFAULT NOW(),
                updated_at  TIMESTAMPTZ   NOT NULL DEFAULT NOW()
            );

            CREATE INDEX IF NOT EXISTS idx_products_status_created ON products(status, created_at DESC);
            CREATE INDEX IF NOT EXISTS idx_products_category_status ON products(category_id, status);
            CREATE INDEX IF NOT EXISTS idx_products_slug ON products(slug);
        `,
    },
    {
        version: 4,
        name: 'create_orders',
        sql: `
            CREATE TABLE IF NOT EXISTS orders (
                id              BIGSERIAL PRIMARY KEY,
                user_id         BIGINT       NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                status          VARCHAR(20)  NOT NULL DEFAULT 'pending'
                                             CHECK (status IN ('pending','confirmed','shipped','delivered','cancelled')),
                total_amount    NUMERIC(10,2) NOT NULL CHECK (total_amount &amp;gt;= 0),
                shipping_address JSONB       NOT NULL,
                notes           TEXT,
                created_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
                updated_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW()
            );

            CREATE TABLE IF NOT EXISTS order_items (
                id         BIGSERIAL PRIMARY KEY,
                order_id   BIGINT        NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
                product_id BIGINT        NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
                quantity   INTEGER       NOT NULL CHECK (quantity &amp;gt; 0),
                unit_price NUMERIC(10,2) NOT NULL CHECK (unit_price &amp;gt; 0),
                UNIQUE (order_id, product_id)
            );

            CREATE INDEX IF NOT EXISTS idx_orders_user_status ON orders(user_id, status);
            CREATE INDEX IF NOT EXISTS idx_orders_status_created ON orders(status, created_at DESC);
            CREATE INDEX IF NOT EXISTS idx_order_items_order ON order_items(order_id);
            CREATE INDEX IF NOT EXISTS idx_order_items_product ON order_items(product_id);
        `,
    },
];

async function runMigrations(): Promise&amp;lt;void&amp;gt; {
    await query(`
        CREATE TABLE IF NOT EXISTS schema_migrations (
            version    INTEGER     NOT NULL PRIMARY KEY,
            name       VARCHAR(255) NOT NULL,
            run_at     TIMESTAMPTZ NOT NULL DEFAULT NOW()
        )
    `);

    const applied = await query&amp;lt;{ version: number }&amp;gt;('SELECT version FROM schema_migrations ORDER BY version');
    const appliedVersions = new Set(applied.map(r =&amp;gt; r.version));

    for (const migration of migrations) {
        if (appliedVersions.has(migration.version)) continue;

        logger.info(`Running migration ${migration.version}: ${migration.name}`);
        await query(migration.sql);
        await query(
            'INSERT INTO schema_migrations (version, name) VALUES ($1, $2)',
            [migration.version, migration.name]
        );
        logger.info(`Migration ${migration.version} completed`);
    }

    logger.info('All migrations complete');
    await closePool();
}

runMigrations().catch((err) =&amp;gt; {
    logger.error('Migration failed', { error: (err as Error).message });
    process.exit(1);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  JWT Utilities
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import jwt from 'jsonwebtoken';
import { config } from '../config';
import { UnauthorizedError } from './errors';

export interface TokenPayload {
    sub:      number;
    username: string;
    is_admin: boolean;
    type:     'access' | 'refresh';
}

export function signAccessToken(payload: Omit&amp;lt;TokenPayload, 'type'&amp;gt;): string {
    return jwt.sign(
        { ...payload, type: 'access' },
        config.JWT_ACCESS_SECRET,
        { expiresIn: config.JWT_ACCESS_EXPIRES, algorithm: 'HS256' }
    );
}

export function signRefreshToken(payload: Omit&amp;lt;TokenPayload, 'type'&amp;gt;): string {
    return jwt.sign(
        { ...payload, type: 'refresh' },
        config.JWT_REFRESH_SECRET,
        { expiresIn: config.JWT_REFRESH_EXPIRES, algorithm: 'HS256' }
    );
}

export function verifyAccessToken(token: string): TokenPayload {
    try {
        const payload = jwt.verify(token, config.JWT_ACCESS_SECRET) as TokenPayload;
        if (payload.type !== 'access') throw new Error('Wrong token type');
        return payload;
    } catch {
        throw new UnauthorizedError('Invalid or expired access token');
    }
}

export function verifyRefreshToken(token: string): TokenPayload {
    try {
        const payload = jwt.verify(token, config.JWT_REFRESH_SECRET) as TokenPayload;
        if (payload.type !== 'refresh') throw new Error('Wrong token type');
        return payload;
    } catch {
        throw new UnauthorizedError('Invalid or expired refresh token');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Express App and Middleware
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express, { Request, Response, NextFunction } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import { config } from './config';
import { router } from './routes';
import { errorHandler } from './middleware/errorHandler';
import { requestLogger } from './middleware/requestLogger';
import { logger } from './utils/logger';

const app = express();

app.use(helmet());
app.use(cors({
    origin: config.CORS_ORIGINS.split(',').map(o =&amp;gt; o.trim()),
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID', 'Idempotency-Key'],
}));
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));
app.use(requestLogger);

app.get('/health/live', (_req: Request, res: Response) =&amp;gt; {
    res.json({ status: 'alive', timestamp: new Date().toISOString() });
});

app.get('/health/ready', async (_req: Request, res: Response) =&amp;gt; {
    const checks: Record&amp;lt;string, { status: string; latency_ms?: number; error?: string }&amp;gt; = {};

    const start = Date.now();
    try {
        const { query } = await import('./database');
        await query('SELECT 1');
        checks['database'] = { status: 'ok', latency_ms: Date.now() - start };
    } catch (err) {
        checks['database'] = { status: 'error', error: (err as Error).message };
    }

    const ready = Object.values(checks).every(c =&amp;gt; c.status === 'ok');
    res.status(ready ? 200 : 503).json({
        status: ready ? 'ready' : 'not_ready',
        checks,
        timestamp: new Date().toISOString(),
    });
});

app.use('/api/v1', router);

app.use((_req: Request, res: Response) =&amp;gt; {
    res.status(404).json({
        error: { code: 'NOT_FOUND', message: 'The requested endpoint does not exist' }
    });
});

app.use(errorHandler);

export { app };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;helmet()&lt;/code&gt; sets security-relevant HTTP headers: &lt;code&gt;X-Content-Type-Options&lt;/code&gt;, &lt;code&gt;X-Frame-Options&lt;/code&gt;, &lt;code&gt;Content-Security-Policy&lt;/code&gt;, and several others. One line of middleware that closes several common attack vectors.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;express.json({ limit: '1mb' })&lt;/code&gt; parses JSON request bodies. The 1MB limit prevents clients from crashing your server by sending enormous payloads.&lt;/p&gt;

&lt;h2&gt;
  
  
  Request Logger Middleware
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Request, Response, NextFunction } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '../utils/logger';

export function requestLogger(req: Request, res: Response, next: NextFunction): void {
    const requestId = (req.headers['x-request-id'] as string) ?? uuidv4();
    const start = Date.now();

    req.requestId = requestId;
    res.setHeader('X-Request-ID', requestId);

    res.on('finish', () =&amp;gt; {
        const duration = Date.now() - start;
        const level = res.statusCode &amp;gt;= 500 ? 'error'
                    : res.statusCode &amp;gt;= 400 ? 'warn'
                    : 'info';

        logger[level](`${req.method} ${req.path}`, {
            request_id: requestId,
            method:     req.method,
            path:       req.path,
            status:     res.statusCode,
            duration_ms: duration,
            ip:         req.ip,
            user_id:    req.user?.id,
        });
    });

    next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Express type augmentation (&lt;code&gt;src/types/express.d.ts&lt;/code&gt;):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { TokenPayload } from '../utils/jwt';

declare global {
    namespace Express {
        interface Request {
            user?:      TokenPayload;
            requestId?: string;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Auth Middleware
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Request, Response, NextFunction } from 'express';
import { verifyAccessToken } from '../utils/jwt';
import { UnauthorizedError, ForbiddenError } from '../utils/errors';

export function authenticate(req: Request, _res: Response, next: NextFunction): void {
    const header = req.headers.authorization;
    if (!header?.startsWith('Bearer ')) {
        throw new UnauthorizedError('Bearer token required');
    }

    const token = header.slice(7);
    req.user = verifyAccessToken(token);
    next();
}

export function requireAdmin(req: Request, _res: Response, next: NextFunction): void {
    if (!req.user) throw new UnauthorizedError();
    if (!req.user.is_admin) throw new ForbiddenError('Admin access required');
    next();
}

export function optionalAuth(req: Request, _res: Response, next: NextFunction): void {
    const header = req.headers.authorization;
    if (header?.startsWith('Bearer ')) {
        try {
            req.user = verifyAccessToken(header.slice(7));
        } catch {
            // Not authenticated — continue without user
        }
    }
    next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Validation Middleware
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Request, Response, NextFunction } from 'express';
import { z, ZodSchema, ZodError } from 'zod';
import { ValidationError } from '../utils/errors';

type ValidationTarget = 'body' | 'query' | 'params';

export function validate&amp;lt;T&amp;gt;(schema: ZodSchema&amp;lt;T&amp;gt;, target: ValidationTarget = 'body') {
    return (req: Request, _res: Response, next: NextFunction): void =&amp;gt; {
        const result = schema.safeParse(req[target]);
        if (!result.success) {
            const details = result.error.issues.map((issue: ZodError['issues'][number]) =&amp;gt; ({
                field:   issue.path.join('.'),
                message: issue.message,
            }));
            throw new ValidationError(details);
        }
        req[target] = result.data;
        next();
    };
}

export const schemas = {
    register: z.object({
        username: z.string().min(3).max(80).regex(/^[a-zA-Z0-9_-]+$/, 'Only letters, numbers, underscores and hyphens'),
        email:    z.string().email(),
        password: z.string().min(8).max(128),
    }),

    login: z.object({
        login:    z.string().min(1),
        password: z.string().min(1),
    }),

    createProduct: z.object({
        name:        z.string().min(1).max(255),
        description: z.string().min(1),
        price:       z.number().positive(),
        stock:       z.number().int().nonnegative().default(0),
        category_id: z.number().int().positive(),
        status:      z.enum(['draft', 'active', 'archived']).default('draft'),
    }),

    updateProduct: z.object({
        name:        z.string().min(1).max(255).optional(),
        description: z.string().min(1).optional(),
        price:       z.number().positive().optional(),
        stock:       z.number().int().nonnegative().optional(),
        category_id: z.number().int().positive().optional(),
        status:      z.enum(['draft', 'active', 'archived']).optional(),
    }),

    createOrder: z.object({
        items: z.array(z.object({
            product_id: z.number().int().positive(),
            quantity:   z.number().int().positive(),
        })).min(1, 'Order must contain at least one item'),
        shipping_address: z.object({
            name:    z.string().min(1),
            street:  z.string().min(1),
            city:    z.string().min(1),
            country: z.string().length(2),
            postal:  z.string().min(1),
        }),
        notes: z.string().max(1000).optional(),
    }),

    pagination: z.object({
        page:     z.coerce.number().int().positive().default(1),
        per_page: z.coerce.number().int().positive().max(100).default(20),
        sort:     z.string().optional(),
        order:    z.enum(['asc', 'desc']).default('desc'),
    }),

    productSearch: z.object({
        status:   z.enum(['draft', 'active', 'archived']).optional(),
        category: z.string().optional(),
        search:   z.string().max(100).optional(),
        min_price: z.coerce.number().positive().optional(),
        max_price: z.coerce.number().positive().optional(),
    }),
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Zod validates and transforms input in one step. &lt;code&gt;z.coerce.number()&lt;/code&gt; converts the string &lt;code&gt;"1"&lt;/code&gt; from a query parameter to the number &lt;code&gt;1&lt;/code&gt;. &lt;code&gt;z.string().email()&lt;/code&gt; validates and normalizes email format. When validation fails, Zod produces detailed error messages that map to specific fields. The &lt;code&gt;ValidationError&lt;/code&gt; class carries those field-level details to the client.&lt;/p&gt;

&lt;h2&gt;
  
  
  Error Handler
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Request, Response, NextFunction } from 'express';
import { AppError } from '../utils/errors';
import { logger } from '../utils/logger';
import { config } from '../config';

export function errorHandler(
    err: Error,
    req: Request,
    res: Response,
    _next: NextFunction
): void {
    if (err instanceof AppError) {
        if (err.statusCode &amp;gt;= 500) {
            logger.error('Application error', {
                request_id: req.requestId,
                code:       err.code,
                message:    err.message,
                stack:      err.stack,
            });
        }

        res.status(err.statusCode).json({
            error: {
                code:       err.code,
                message:    err.message,
                ...(err.details ? { details: err.details } : {}),
                request_id: req.requestId,
            },
        });
        return;
    }

    logger.error('Unhandled error', {
        request_id: req.requestId,
        message:    err.message,
        stack:      err.stack,
    });

    res.status(500).json({
        error: {
            code:       'INTERNAL_SERVER_ERROR',
            message:    config.NODE_ENV === 'production' ? 'An internal error occurred' : err.message,
            request_id: req.requestId,
        },
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One error handler handles all errors. Application errors (subclasses of &lt;code&gt;AppError&lt;/code&gt;) get their status code and error code sent to the client. Unknown errors get a 500 with a generic message in production (you do not want to leak stack traces to users) and the actual message in development. Both cases log the full error with stack trace.&lt;/p&gt;

&lt;h2&gt;
  
  
  Auth Routes
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Router, Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import { query, queryOne, transaction } from '../database';
import { signAccessToken, signRefreshToken, verifyRefreshToken } from '../utils/jwt';
import { authenticate } from '../middleware/auth';
import { validate, schemas } from '../middleware/validate';
import { config } from '../config';
import { ConflictError, UnauthorizedError, NotFoundError } from '../utils/errors';
import { logger } from '../utils/logger';

const router = Router();

router.post('/register', validate(schemas.register), async (req: Request, res: Response) =&amp;gt; {
    const { username, email, password } = req.body as {
        username: string; email: string; password: string;
    };

    const existing = await queryOne&amp;lt;{ id: number }&amp;gt;(
        'SELECT id FROM users WHERE email = $1 OR username = $2',
        [email, username]
    );
    if (existing) throw new ConflictError('Username or email already registered');

    const passwordHash = await bcrypt.hash(password, config.BCRYPT_ROUNDS);
    const user = await queryOne&amp;lt;{ id: number; username: string; email: string; is_admin: boolean }&amp;gt;(
        `INSERT INTO users (username, email, password_hash)
         VALUES ($1, $2, $3)
         RETURNING id, username, email, is_admin`,
        [username, email, passwordHash]
    );

    if (!user) throw new Error('Failed to create user');

    const tokenPayload = { sub: user.id, username: user.username, is_admin: user.is_admin };
    const accessToken   = signAccessToken(tokenPayload);
    const refreshToken  = signRefreshToken(tokenPayload);

    const tokenHash = crypto.createHash('sha256').update(refreshToken).digest('hex');
    const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    await query(
        'INSERT INTO refresh_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
        [user.id, tokenHash, expiresAt]
    );

    logger.info('User registered', { user_id: user.id, username: user.username });

    res.status(201).json({
        data: { id: user.id, username: user.username, email: user.email },
        access_token:  accessToken,
        refresh_token: refreshToken,
    });
});

router.post('/login', validate(schemas.login), async (req: Request, res: Response) =&amp;gt; {
    const { login, password } = req.body as { login: string; password: string };

    const user = await queryOne&amp;lt;{
        id: number; username: string; email: string;
        password_hash: string; is_active: boolean; is_admin: boolean;
    }&amp;gt;(
        'SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE email = $1 OR username = $1',
        [login]
    );

    if (!user || !(await bcrypt.compare(password, user.password_hash))) {
        throw new UnauthorizedError('Invalid credentials');
    }

    if (!user.is_active) throw new UnauthorizedError('Account is disabled');

    await query('UPDATE users SET last_login = NOW() WHERE id = $1', [user.id]);

    const tokenPayload = { sub: user.id, username: user.username, is_admin: user.is_admin };
    const accessToken   = signAccessToken(tokenPayload);
    const refreshToken  = signRefreshToken(tokenPayload);

    const tokenHash = crypto.createHash('sha256').update(refreshToken).digest('hex');
    const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    await query(
        'INSERT INTO refresh_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
        [user.id, tokenHash, expiresAt]
    );

    res.json({
        data: { id: user.id, username: user.username, email: user.email },
        access_token:  accessToken,
        refresh_token: refreshToken,
    });
});

router.post('/refresh', async (req: Request, res: Response) =&amp;gt; {
    const { refresh_token } = req.body as { refresh_token?: string };
    if (!refresh_token) throw new UnauthorizedError('Refresh token required');

    const payload   = verifyRefreshToken(refresh_token);
    const tokenHash = crypto.createHash('sha256').update(refresh_token).digest('hex');

    const stored = await queryOne&amp;lt;{ id: number; revoked: boolean; expires_at: Date }&amp;gt;(
        'SELECT id, revoked, expires_at FROM refresh_tokens WHERE token_hash = $1',
        [tokenHash]
    );

    if (!stored || stored.revoked || stored.expires_at &amp;lt; new Date()) {
        throw new UnauthorizedError('Invalid or expired refresh token');
    }

    await query('UPDATE refresh_tokens SET revoked = true WHERE id = $1', [stored.id]);

    const user = await queryOne&amp;lt;{ id: number; username: string; is_active: boolean; is_admin: boolean }&amp;gt;(
        'SELECT id, username, is_active, is_admin FROM users WHERE id = $1',
        [payload.sub]
    );

    if (!user || !user.is_active) throw new UnauthorizedError('User not found or inactive');

    const tokenPayload = { sub: user.id, username: user.username, is_admin: user.is_admin };
    const newAccess    = signAccessToken(tokenPayload);
    const newRefresh   = signRefreshToken(tokenPayload);

    const newHash    = crypto.createHash('sha256').update(newRefresh).digest('hex');
    const newExpires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    await query(
        'INSERT INTO refresh_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
        [user.id, newHash, newExpires]
    );

    res.json({ access_token: newAccess, refresh_token: newRefresh });
});

router.post('/logout', authenticate, async (req: Request, res: Response) =&amp;gt; {
    await query(
        'UPDATE refresh_tokens SET revoked = true WHERE user_id = $1 AND revoked = false',
        [req.user!.sub]
    );
    res.status(204).send();
});

router.get('/me', authenticate, async (req: Request, res: Response) =&amp;gt; {
    const user = await queryOne&amp;lt;{ id: number; username: string; email: string; created_at: Date }&amp;gt;(
        'SELECT id, username, email, created_at FROM users WHERE id = $1',
        [req.user!.sub]
    );
    if (!user) throw new NotFoundError('User');
    res.json({ data: user });
});

export default router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The refresh token rotation pattern (revoke the old token, issue a new one) prevents refresh token replay attacks. If a stolen token is used, the legitimate user's next refresh attempt fails because the token was already revoked, alerting them that their session was compromised.&lt;/p&gt;

&lt;p&gt;Refresh tokens are stored as SHA-256 hashes, not plaintext. If the database is compromised, attackers get hashes, not the tokens themselves.&lt;/p&gt;

&lt;h2&gt;
  
  
  Products Routes
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Router, Request, Response } from 'express';
import { query, queryOne, transaction } from '../database';
import { authenticate, requireAdmin, optionalAuth } from '../middleware/auth';
import { validate, schemas } from '../middleware/validate';
import { NotFoundError, ForbiddenError, ConflictError } from '../utils/errors';

const router = Router();

router.get('/', optionalAuth, validate(schemas.pagination, 'query'), validate(schemas.productSearch, 'query'),
async (req: Request, res: Response) =&amp;gt; {
    const { page, per_page, order } = req.query as any;
    const { status, category, search, min_price, max_price } = req.query as any;

    const conditions: string[] = [];
    const params: unknown[] = [];
    let idx = 1;

    const statusFilter = status ?? (req.user?.is_admin ? undefined : 'active');
    if (statusFilter) {
        conditions.push(`p.status = $${idx++}`);
        params.push(statusFilter);
    }

    if (category) {
        conditions.push(`c.slug = $${idx++}`);
        params.push(category);
    }
    if (search) {
        conditions.push(`(p.name ILIKE $${idx} OR p.description ILIKE $${idx})`);
        params.push(`%${search}%`);
        idx++;
    }
    if (min_price) { conditions.push(`p.price &amp;gt;= $${idx++}`); params.push(min_price); }
    if (max_price) { conditions.push(`p.price &amp;lt;= $${idx++}`); params.push(max_price); }

    const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';

    const [countRow] = await query&amp;lt;{ total: string }&amp;gt;(
        `SELECT COUNT(*) AS total FROM products p
         LEFT JOIN categories c ON c.id = p.category_id ${where}`,
        params
    );
    const total = parseInt(countRow?.total ?? '0', 10);

    const offset = (page - 1) * per_page;
    const rows = await query(
        `SELECT p.id, p.name, p.slug, p.price, p.stock, p.status,
                p.created_at, c.name AS category_name, c.slug AS category_slug
         FROM products p
         LEFT JOIN categories c ON c.id = p.category_id
         ${where}
         ORDER BY p.created_at ${order === 'asc' ? 'ASC' : 'DESC'}
         LIMIT $${idx} OFFSET $${idx + 1}`,
        [...params, per_page, offset]
    );

    res.json({
        data: rows,
        pagination: {
            page, per_page, total,
            pages: Math.ceil(total / per_page),
        },
    });
});

router.get('/:slug', async (req: Request, res: Response) =&amp;gt; {
    const product = await queryOne(
        `SELECT p.*, c.name AS category_name, c.slug AS category_slug,
                u.username AS owner_username
         FROM products p
         LEFT JOIN categories c ON c.id = p.category_id
         LEFT JOIN users u ON u.id = p.owner_id
         WHERE p.slug = $1`,
        [req.params['slug']]
    );
    if (!product) throw new NotFoundError('Product', req.params['slug']);
    res.json({ data: product });
});

router.post('/', authenticate, validate(schemas.createProduct), async (req: Request, res: Response) =&amp;gt; {
    const { name, description, price, stock, category_id, status } = req.body;

    const slug = generateSlug(name);
    const existing = await queryOne&amp;lt;{ id: number }&amp;gt;('SELECT id FROM products WHERE slug = $1', [slug]);
    const finalSlug = existing ? `${slug}-${Date.now().toString(36)}` : slug;

    const product = await queryOne(
        `INSERT INTO products (name, slug, description, price, stock, category_id, owner_id, status)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
         RETURNING *`,
        [name, finalSlug, description, price, stock, category_id, req.user!.sub, status]
    );

    res.status(201).json({ data: product });
});

router.patch('/:id', authenticate, validate(schemas.updateProduct), async (req: Request, res: Response) =&amp;gt; {
    const id = parseInt(req.params['id']!, 10);
    const product = await queryOne&amp;lt;{ id: number; owner_id: number }&amp;gt;(
        'SELECT id, owner_id FROM products WHERE id = $1', [id]
    );
    if (!product) throw new NotFoundError('Product', id);
    if (product.owner_id !== req.user!.sub &amp;amp;&amp;amp; !req.user!.is_admin) {
        throw new ForbiddenError('You do not own this product');
    }

    const fields = req.body as Record&amp;lt;string, unknown&amp;gt;;
    const updates: string[] = [];
    const params: unknown[] = [];
    let idx = 1;

    const allowed = ['name', 'description', 'price', 'stock', 'category_id', 'status'];
    for (const field of allowed) {
        if (field in fields) {
            updates.push(`${field} = $${idx++}`);
            params.push(fields[field]);
        }
    }
    if (!updates.length) { res.json({ data: product }); return; }

    updates.push(`updated_at = NOW()`);
    params.push(id);

    const updated = await queryOne(
        `UPDATE products SET ${updates.join(', ')} WHERE id = $${idx} RETURNING *`,
        params
    );
    res.json({ data: updated });
});

router.delete('/:id', authenticate, async (req: Request, res: Response) =&amp;gt; {
    const id = parseInt(req.params['id']!, 10);
    const product = await queryOne&amp;lt;{ id: number; owner_id: number }&amp;gt;(
        'SELECT id, owner_id FROM products WHERE id = $1', [id]
    );
    if (!product) throw new NotFoundError('Product', id);
    if (product.owner_id !== req.user!.sub &amp;amp;&amp;amp; !req.user!.is_admin) {
        throw new ForbiddenError('You do not own this product');
    }

    await query('DELETE FROM products WHERE id = $1', [id]);
    res.status(204).send();
});

function generateSlug(name: string): string {
    return name
        .toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .trim();
}

export default router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Server Entry Point and Graceful Shutdown
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { app } from './app';
import { config } from './config';
import { closePool } from './database';
import { logger } from './utils/logger';

const server = app.listen(config.PORT, () =&amp;gt; {
    logger.info('Server started', { port: config.PORT, env: config.NODE_ENV });
});

async function shutdown(signal: string): Promise&amp;lt;void&amp;gt; {
    logger.info(`Received ${signal}. Starting graceful shutdown`);

    server.close(async () =&amp;gt; {
        logger.info('HTTP server closed');
        try {
            await closePool();
            logger.info('Graceful shutdown complete');
            process.exit(0);
        } catch (err) {
            logger.error('Error during shutdown', { error: (err as Error).message });
            process.exit(1);
        }
    });

    setTimeout(() =&amp;gt; {
        logger.error('Forced shutdown after timeout');
        process.exit(1);
    }, 30000);
}

process.on('SIGTERM', () =&amp;gt; void shutdown('SIGTERM'));
process.on('SIGINT',  () =&amp;gt; void shutdown('SIGINT'));
process.on('uncaughtException', (err) =&amp;gt; {
    logger.error('Uncaught exception', { error: err.message, stack: err.stack });
    void shutdown('uncaughtException');
});
process.on('unhandledRejection', (reason) =&amp;gt; {
    logger.error('Unhandled rejection', { reason: String(reason) });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Graceful shutdown lets in-flight requests complete before the server exits. &lt;code&gt;server.close()&lt;/code&gt; stops accepting new connections and calls the callback when all active connections have finished. Without graceful shutdown, a deployment terminates connections mid-request, causing errors for users who happened to be making requests when the deployment happened. The 30-second timeout forces shutdown if requests are taking too long to complete.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import request from 'supertest';
import { app } from '../src/app';
import { query } from '../src/database';

beforeEach(async () =&amp;gt; {
    await query('TRUNCATE TABLE order_items, orders, products, refresh_tokens, users, categories RESTART IDENTITY CASCADE');
    await query("INSERT INTO categories (name, slug) VALUES ('Electronics', 'electronics')");
});

describe('POST /api/v1/auth/register', () =&amp;gt; {
    it('creates a user and returns tokens', async () =&amp;gt; {
        const res = await request(app)
            .post('/api/v1/auth/register')
            .send({ username: 'testuser', email: 'test@example.com', password: 'password123' });

        expect(res.status).toBe(201);
        expect(res.body.data.username).toBe('testuser');
        expect(res.body.access_token).toBeDefined();
        expect(res.body.refresh_token).toBeDefined();
    });

    it('returns 409 for duplicate email', async () =&amp;gt; {
        const payload = { username: 'user1', email: 'dup@example.com', password: 'password123' };
        await request(app).post('/api/v1/auth/register').send(payload);
        const res = await request(app).post('/api/v1/auth/register').send({ ...payload, username: 'user2' });
        expect(res.status).toBe(409);
        expect(res.body.error.code).toBe('CONFLICT');
    });

    it('returns 400 for short password', async () =&amp;gt; {
        const res = await request(app)
            .post('/api/v1/auth/register')
            .send({ username: 'user', email: 'u@example.com', password: 'short' });
        expect(res.status).toBe(400);
        expect(res.body.error.code).toBe('VALIDATION_ERROR');
    });
});

async function registerAndLogin(): Promise&amp;lt;string&amp;gt; {
    await request(app).post('/api/v1/auth/register')
        .send({ username: 'tester', email: 'tester@example.com', password: 'password123' });
    const loginRes = await request(app).post('/api/v1/auth/login')
        .send({ login: 'tester', password: 'password123' });
    return loginRes.body.access_token as string;
}

describe('GET /api/v1/products', () =&amp;gt; {
    it('returns empty list when no products', async () =&amp;gt; {
        const res = await request(app).get('/api/v1/products');
        expect(res.status).toBe(200);
        expect(res.body.data).toEqual([]);
        expect(res.body.pagination.total).toBe(0);
    });

    it('returns active products only for unauthenticated users', async () =&amp;gt; {
        const token = await registerAndLogin();
        await request(app).post('/api/v1/products').set('Authorization', `Bearer ${token}`)
            .send({ name: 'Draft Product', description: 'desc', price: 9.99, stock: 10, category_id: 1, status: 'draft' });
        await request(app).post('/api/v1/products').set('Authorization', `Bearer ${token}`)
            .send({ name: 'Active Product', description: 'desc', price: 9.99, stock: 10, category_id: 1, status: 'active' });

        const res = await request(app).get('/api/v1/products');
        expect(res.status).toBe(200);
        expect(res.body.data).toHaveLength(1);
        expect(res.body.data[0].name).toBe('Active Product');
    });
});

describe('POST /api/v1/products', () =&amp;gt; {
    it('creates a product when authenticated', async () =&amp;gt; {
        const token = await registerAndLogin();
        const res = await request(app).post('/api/v1/products')
            .set('Authorization', `Bearer ${token}`)
            .send({ name: 'Test Product', description: 'A product', price: 19.99, stock: 50, category_id: 1 });

        expect(res.status).toBe(201);
        expect(res.body.data.name).toBe('Test Product');
        expect(res.body.data.slug).toBeDefined();
    });

    it('returns 401 without authentication', async () =&amp;gt; {
        const res = await request(app).post('/api/v1/products')
            .send({ name: 'Product', description: 'desc', price: 9.99, category_id: 1 });
        expect(res.status).toBe(401);
    });

    it('returns 400 for negative price', async () =&amp;gt; {
        const token = await registerAndLogin();
        const res = await request(app).post('/api/v1/products')
            .set('Authorization', `Bearer ${token}`)
            .send({ name: 'Bad Product', description: 'desc', price: -5, category_id: 1 });
        expect(res.status).toBe(400);
        expect(res.body.error.details).toContainEqual(
            expect.objectContaining({ field: 'price' })
        );
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Supertest makes HTTP requests against your Express app without starting a network server. Tests run in-process, which is fast and deterministic. The &lt;code&gt;TRUNCATE ... RESTART IDENTITY CASCADE&lt;/code&gt; before each test resets the database to a clean state. Every test starts with predictable data.&lt;/p&gt;

&lt;p&gt;This is integration testing, not unit testing. Integration tests exercise the full stack: middleware, validation, route handlers, database queries. They catch bugs that unit tests of individual functions miss. They are slower than unit tests but far more valuable for API code where the integration between layers is where bugs live.&lt;/p&gt;

&lt;p&gt;Run the full test suite:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Targeting 80% coverage on your route handlers and middleware is a reasonable starting goal. 100% coverage is usually not worth the effort and produces brittle tests that break when implementation details change.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>api</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Your Minecraft Server Wants Java 25, Not Java 26</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Mon, 23 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/your-minecraft-server-wants-java-25-not-java-26-2g16</link>
      <guid>https://dev.to/sudosecurity/your-minecraft-server-wants-java-25-not-java-26-2g16</guid>
      <description>&lt;p&gt;Every six months, like clockwork, the same question resurfaces in every Minecraft server admin Discord and every r/admincraft thread: &lt;em&gt;"New Java version dropped, should I upgrade?"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;And every six months, the same two camps form. One side says "just stick with LTS, don't touch what works." The other side posts screenshots of someone's personal benchmark running a single-player world and declares Java 26 is 40% faster. Nobody actually digs into the specifics. Nobody maps the JVM engineering work onto what a Minecraft server actually does. The conversation dies, everyone stays on Java 21, and we do it again in six months.&lt;/p&gt;

&lt;p&gt;This is that article, but done properly.&lt;/p&gt;

&lt;p&gt;I want to actually answer whether you should upgrade your &lt;a href="https://www.minecraft.net/en-us/about-minecraft" rel="noopener noreferrer"&gt;Minecraft&lt;/a&gt; server from &lt;a href="https://sudosecurity.org/what-is-java/" rel="noopener noreferrer"&gt;Java&lt;/a&gt; 21 — which is what almost everyone is running — to Java 22, 23, 24, 25, or go all the way to Java 26. That means understanding what each version actually changed in the JVM, mapping those changes to what a Minecraft server actually does with the JVM, and giving you a real decision framework at the end that isn't just "it depends."&lt;/p&gt;

&lt;p&gt;Spoiler: it does depend. But on specific, concrete things we can reason about.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Actually Makes a Minecraft Server Slow?
&lt;/h2&gt;

&lt;p&gt;Before we talk Java versions, we need to establish what a Minecraft server actually puts the JVM through. Because "is Java X faster than Java Y" is meaningless unless you understand what kind of work is being done.&lt;/p&gt;

&lt;p&gt;A Minecraft server runs one main tick loop at a target of 20 ticks per second. Each tick has a 50 millisecond budget. Inside that 50ms, the server needs to: process all player movement and input, run all entity AI pathfinding, update redstone contraptions, handle block updates, run mob spawning logic, advance scheduled tasks, execute any synchronous plugin code, and then send the results to every connected client. Every tick. 20 times per second. With no exceptions.&lt;/p&gt;

&lt;p&gt;When you can't finish all of that within 50ms, your TPS — ticks per second — drops below 20. Players feel this as rubber-banding, delayed block placement, inventory lag, and the general feeling that the server is "heavy." When TPS drops to 15 you're missing 25% of your ticks. Below 10 and the game is genuinely unplayable.&lt;/p&gt;

&lt;p&gt;The JVM contributes to lag in three main ways:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Garbage Collection Pauses.&lt;/strong&gt; &lt;a href="https://sudosecurity.org/what-is-java/" rel="noopener noreferrer"&gt;Java&lt;/a&gt; is a garbage-collected language. Memory that your program allocates and stops using gets cleaned up by the garbage collector. The problem is that some collection work requires the JVM to pause &lt;em&gt;all&lt;/em&gt; running threads — including your server's main tick thread. When this happens, your server just freezes. For however long the GC runs. This is called a stop-the-world pause. A 200ms GC pause is four missing ticks. Players see rubber-banding. This is the single biggest JVM-related source of Minecraft server lag, and it's the main reason which GC you run and how you configure it matters enormously.&lt;/p&gt;

&lt;p&gt;To understand the scale of the problem: &lt;a href="https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/" rel="noopener noreferrer"&gt;Aikar's research&lt;/a&gt; — the guy whose G1GC flags the entire community has been running for years — documented that a 30-player Minecraft server generates at least 800 megabytes of heap allocations per second. Not per minute. Per second. Most of those objects are things like &lt;code&gt;BlockPos&lt;/code&gt; instances that are created, used once, and immediately discarded. That rate of object churn is what GC is fighting against constantly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JIT Warmup.&lt;/strong&gt; Java bytecode doesn't run directly as machine code. The &lt;a href="https://en.wikipedia.org/wiki/Java_virtual_machine" rel="noopener noreferrer"&gt;JVM&lt;/a&gt; interprets it first, then a tiered JIT compiler watches which code paths are "hot" and compiles them to native machine code. The main JIT compiler, C2, produces highly optimized code but takes time to identify what to compile and time to actually compile it. A freshly started Minecraft server is operating below peak performance for its first 5-20 minutes as this warmup happens. The AOT caching work landing across Java 24-26 is specifically about cutting this warmup time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CPU Throughput — The JIT's Code Quality.&lt;/strong&gt; Once warm, how good is the native code the JIT generates? How efficiently is it using your CPU's capabilities? This is where things like auto-vectorization, loop optimizations, and the quality of compiled write barriers matter. Better JIT = more game simulation completed per CPU cycle = more headroom before your tick budget runs out.&lt;/p&gt;

&lt;p&gt;Understand these three things and you can evaluate every JVM change in terms of how it moves the needle on a Minecraft server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Java 21 is still a Fine Choice
&lt;/h2&gt;

&lt;p&gt;Java 21 is the current Long-Term Support release. &lt;a href="https://www.minecraft.net/en-us/article/minecraft-java-edition-1-20-5" rel="noopener noreferrer"&gt;Mojang officially requires it for Minecraft 1.20.5 and later.&lt;/a&gt; It gets premier support until at least 2028. If you're running a stable 1.21.x server, Java 21 is the right call and nothing in this article should make you feel bad about that.&lt;/p&gt;

&lt;p&gt;But Java 21 did bring genuinely significant things that established the foundation for everything since:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generational ZGC&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/439" rel="noopener noreferrer"&gt;JEP 439&lt;/a&gt;) landed as a production-ready feature. This matters a lot. The Z Garbage Collector existed before Java 21, but it was non-generational — meaning it treated every single object in your heap equally when deciding what to collect. This is wildly inefficient for Minecraft because the vast majority of objects (all those &lt;code&gt;BlockPos&lt;/code&gt; instances, packet objects, AI calculation results) die within milliseconds of being created. Most objects die young. A generational GC exploits this by collecting the "young generation" of the heap much more frequently and cheaply, only touching the "old generation" occasionally.&lt;/p&gt;

&lt;p&gt;Non-generational ZGC had to scan your entire 8GB+ heap on every collection. Generational ZGC scans the small young generation constantly (cheap, fast) and touches the old generation rarely. The practical result for Minecraft servers: much lower and more consistent GC pause times. The &lt;a href="https://github.com/Obydux/Minecraft-startup-flags" rel="noopener noreferrer"&gt;Obydux research into Minecraft startup flags&lt;/a&gt; notes this as the most significant GC advancement for Minecraft in years, and large-server Minecraft communities have validated it. On a 100+ player server with 16GB+ heap allocated, generational ZGC can bring peak GC pause times from 200+ms (G1GC spikes) down to single-digit milliseconds consistently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Virtual Threads&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/444" rel="noopener noreferrer"&gt;JEP 444&lt;/a&gt;, Project Loom) finalized. The main Minecraft tick loop is still single-threaded and virtual threads don't change that. But &lt;a href="https://papermc.io/" rel="noopener noreferrer"&gt;PaperMC&lt;/a&gt; and its derivatives use threads for async chunk loading, networking (Netty), and various background tasks. Virtual threads make those background operations more scalable. The &lt;a href="https://www.leafmc.one/docs/how-to/java-flags" rel="noopener noreferrer"&gt;Leaf MC documentation&lt;/a&gt; notes that the modern JVM (Java 21+) has gotten good enough at handling Minecraft that even default GC configuration produces reasonable results — which would have been an absurd statement on Java 8.&lt;/p&gt;

&lt;h2&gt;
  
  
  We can skip Java 22
&lt;/h2&gt;

&lt;p&gt;Java 22 was a short-term release — six months of Premier support, released March 2024. It's end-of-life. If someone is running Java 22 on a production server right now they should upgrade immediately, either to 21 LTS if staying on current stable Minecraft, or to 25 LTS for forward compatibility.&lt;/p&gt;

&lt;p&gt;That said, Java 22 shipped work that subsequent versions built on. The &lt;a href="https://openjdk.org/jeps/454" rel="noopener noreferrer"&gt;Foreign Function and Memory API&lt;/a&gt; (from Project Panama) finalized in Java 22. This is the "native access" work that &lt;a href="https://madelinemiller.dev/blog/java-future-minecraft/" rel="noopener noreferrer"&gt;Maddy Miller's Java/Minecraft analysis&lt;/a&gt; has highlighted as relevant to Netty (Minecraft's networking library) and LWJGL (the rendering library). Panama allows Java to interop with native CPU capabilities more efficiently, and Netty can theoretically use this for faster network I/O. The performance gains here are upstream library improvements — they happen when Netty and LWJGL ship updated versions, not just when you upgrade Java.&lt;/p&gt;

&lt;p&gt;Java 22 also shipped G1GC write barrier improvements that were the early work of what became the major optimization in Java 24. Think of Java 22 as laying the groundwork.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bottom line on Java 22: Don't run it. It's EOL. But understand it as a step in the sequence.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The C2 MergeStore Optimization — This One Is Specifically Relevant to Minecraft
&lt;/h2&gt;

&lt;p&gt;Java 23 shipped something that I want to explain in detail because it's directly relevant to what a Minecraft server does all day: the &lt;strong&gt;C2 MergeStore optimization&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://inside.java/2025/10/20/jdk-25-performance-improvements/" rel="noopener noreferrer"&gt;Inside.java JDK 25 performance article&lt;/a&gt; describes this as allowing the C2 JIT compiler to merge byte-by-byte store operations into wider primitive stores. What that means in plain language: code that reads and writes byte arrays gets faster because the CPU can do multiple bytes of work in a single instruction instead of processing them individually.&lt;/p&gt;

&lt;p&gt;You may be wondering why this is specifically relevant to a Minecraft server. Here's the thing: Minecraft's network stack runs on &lt;a href="https://netty.io/" rel="noopener noreferrer"&gt;Netty&lt;/a&gt;, and every packet you send to every player gets serialized into a byte buffer. Every chunk of world data that gets sent when players move is byte arrays. Every NBT tag that describes block state, inventory contents, or entity data is processed as byte arrays. The packet encoding and decoding that happens every single tick, for every single connected player, goes through exactly this kind of byte-level operation. The C2 MergeStore optimization makes this work more efficient, and on a server under load, that kind of throughput improvement compounds.&lt;/p&gt;

&lt;p&gt;Java 23 also fixed the &lt;strong&gt;secondary supertype cache&lt;/strong&gt; scalability problem on x64 and AArch64 (&lt;a href="https://bugs.openjdk.org/browse/JDK-8180450" rel="noopener noreferrer"&gt;JDK-8180450&lt;/a&gt;). This is a JVM internal data structure used for &lt;code&gt;instanceof&lt;/code&gt; checks and virtual method dispatch. The old implementation used a single-element cache that caused catastrophic cache line ping-ponging on multi-threaded workloads — when multiple threads are rapidly checking different type hierarchies (which they are on any Paper server doing async chunk work), they'd constantly invalidate each other's cached values. The new hash-table based approach eliminates this contention. For &lt;a href="https://papermc.io/" rel="noopener noreferrer"&gt;Paper&lt;/a&gt; with its async chunk loading pipeline, this matters.&lt;/p&gt;

&lt;p&gt;Java 23 is also the version where &lt;strong&gt;non-generational ZGC was deprecated&lt;/strong&gt;. That's the signal: if you're using &lt;code&gt;-XX:+UseZGC&lt;/code&gt; without &lt;code&gt;-XX:+ZGenerational&lt;/code&gt;, your ZGC setup is now running on deprecated code and will stop working in Java 24+. In Java 24 and beyond, &lt;code&gt;-XX:+UseZGC&lt;/code&gt; automatically means generational mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Java 23 in summary for servers: Real improvements from MergeStore and the supertype cache fix. Still a short-term release, still EOL now. Don't run it in production.&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/java-memory-management-jvm-heap-gc-tuning/" rel="noopener noreferrer"&gt;Your Container Is Running SerialGC and Nobody Told You&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  The Big G1GC JIT Win from Java 24
&lt;/h2&gt;

&lt;p&gt;Java 24 is where things get interesting. It shipped &lt;a href="https://openjdk.org/jeps/475" rel="noopener noreferrer"&gt;JEP 475: Late Barrier Expansion for G1&lt;/a&gt;, and this is a meaningful performance improvement if you're running G1GC.&lt;/p&gt;

&lt;p&gt;Here's what it means. G1GC uses "write barriers" — small pieces of code injected around every reference store operation (every time your code stores a reference to an object in a field). These write barriers let the GC track which objects in the old generation point to objects in the new generation. They're necessary for generational GC to work correctly.&lt;/p&gt;

&lt;p&gt;The problem was that G1's write barriers were huge. Each write barrier required over 100 IR (intermediate representation) operations in C2's pipeline. A single write barrier compiled to roughly 50 x64 instructions. Since memory writes happen constantly in any Java program — and in Minecraft they happen on literally every entity update, every block change, every inventory modification — this overhead was significant.&lt;/p&gt;

&lt;p&gt;The previous "early expansion" approach meant C2 was including all those write barrier IR nodes throughout its entire compilation pipeline, even though GC barriers don't benefit from most C2 optimizations. &lt;a href="https://nipafx.dev/inside-java-newscast-82/" rel="noopener noreferrer"&gt;The JDK engineers found&lt;/a&gt; that G1 barrier IR operations were accounting for around &lt;strong&gt;20% of C2's total execution time&lt;/strong&gt;. Moving to "late expansion" — where the barrier instructions are inserted at the very end of compilation instead of being carried through the whole pipeline — eliminates that wasted work while producing equivalent output code.&lt;/p&gt;

&lt;p&gt;The result: &lt;strong&gt;10-20% less JIT compilation work for the combination of G1GC and C2&lt;/strong&gt;. Every method the JIT compiles is cheaper to compile. The server warms up faster. More CPU is available for your actual game logic during warmup. And on an ongoing basis, recompilation of methods as the JIT's optimizer adapts has less overhead.&lt;/p&gt;

&lt;p&gt;Java 24 also shipped the first &lt;strong&gt;AOT cache&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/483" rel="noopener noreferrer"&gt;JEP 483&lt;/a&gt;, Project Leyden). You can now run a "training" session of your server, save the class loading and linking work to a cache file, and subsequent startups skip all that work. Minecraft server startup is notoriously slow — often 60-120 seconds — largely because of class loading, linking, and initial JIT compilation. The AOT cache cuts into that.&lt;/p&gt;

&lt;p&gt;Additionally, &lt;strong&gt;String concatenation got 40% faster at startup&lt;/strong&gt; in Java 24 from a JIT rewrite. Server startup logs and config loading are heavy on string operations. Shaving startup time matters when you're running a server people are waiting to join.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Java 24 in summary: The G1GC JIT improvement is real and directly applicable to Minecraft. The AOT cache is useful for startup time. But it's another STR, end-of-life now. Don't run it.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Java 25 is the upgrade worthy TLS you want
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://openjdk.org/projects/jdk/25/" rel="noopener noreferrer"&gt;Java 25&lt;/a&gt; is the LTS release after Java 21. Premier support through at least 2028. This is the realistic upgrade target for any server admin who wants to get off Java 21.&lt;/p&gt;

&lt;p&gt;Java 25 stacks every improvement from 22, 23, and 24 and adds more on top:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Auto-Vectorization Improvements.&lt;/strong&gt; C2's auto-vectorization — the ability to rewrite plain Java loops to use SIMD (Single Instruction, Multiple Data) CPU instructions automatically — got meaningfully extended. The &lt;a href="https://inside.java/2025/10/20/jdk-25-performance-improvements/" rel="noopener noreferrer"&gt;Inside.java performance article&lt;/a&gt; shows a &lt;code&gt;Math.min&lt;/code&gt;/&lt;code&gt;Math.max&lt;/code&gt; clipping benchmark getting 3-5x speedups on various platforms after auto-vectorization kicks in. The realistic impact on Minecraft code isn't 3-5x across the board — targeted benchmarks are best-case. But the kinds of loops that benefit most are exactly the math-heavy, array-processing code that shows up in pathfinding, chunk compression, physics simulation, and redstone computation. The JIT compiler doing more work for you, on code you didn't have to touch, is always free performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;String::hashCode Constant Folding.&lt;/strong&gt; HashMap lookups where the key is a string constant now get better JIT treatment — the JIT can recognize that &lt;code&gt;"someConstantString".hashCode()&lt;/code&gt; is always the same value and avoid recomputing it. Minecraft plugins use HashMap-based registries constantly: command registration, permission node lookups, material registries, event handler maps. This is a small per-operation improvement that's pervasive enough to compound.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AOT Cache Extended with Method Profiles&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/515" rel="noopener noreferrer"&gt;JEP 515&lt;/a&gt;). Java 24's AOT cache saved class loading state. Java 25's extends it to also save the JIT's profiling information from the training run. This means on startup, instead of the JIT needing to observe which code paths are hot before it can optimize them, it already knows from the saved profiles. The &lt;a href="https://inside.java/2025/10/20/jdk-25-performance-improvements/" rel="noopener noreferrer"&gt;Inside.java article&lt;/a&gt; notes some programs starting 15-25% faster with this versus Java 24 with a similarly trained cache. For a Minecraft server, the period between "server started" and "server performing well" gets shorter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Compact Object Headers&lt;/strong&gt; (&lt;code&gt;-XX:+UseCompactObjectHeaders&lt;/code&gt;). This flag, stabilizing in Java 25, reduces the overhead per Java object header from 96-128 bits down to 64 bits. Every object in your JVM heap has a header. Minecraft creates millions of small objects — &lt;code&gt;BlockPos&lt;/code&gt;, &lt;code&gt;Vec3d&lt;/code&gt;, &lt;code&gt;ChunkPos&lt;/code&gt;, packet objects, entity state snapshots. Reducing header size reduces heap pressure across all of them. The &lt;a href="https://github.com/Obydux/Minecraft-startup-flags" rel="noopener noreferrer"&gt;Obydux Minecraft flags analysis&lt;/a&gt; notes this can reduce memory usage by up to 20% in some cases. In Minecraft's workload the real number will be less dramatic, but any heap pressure reduction means the GC needs to run less often, which means fewer pauses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generational Shenandoah finalized.&lt;/strong&gt; Shenandoah is a concurrent, low-pause GC available in Red Hat and Adoptium builds. Java 25 finalizes its generational mode. This doesn't replace generational ZGC as the recommendation for high-player-count servers, but it does mean Shenandoah is now a viable tested option for server admins who want a concurrent GC but hit issues with ZGC's memory overhead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GraalVM CE JIT improvements.&lt;/strong&gt; Java 25's &lt;a href="https://www.graalvm.org/" rel="noopener noreferrer"&gt;GraalVM Community Edition&lt;/a&gt; JIT produces better code in more situations. If you're using GraalVM for your server (the &lt;a href="https://github.com/brucethemoose/Minecraft-Performance-Flags-Benchmarks" rel="noopener noreferrer"&gt;brucethemoose benchmark repository&lt;/a&gt; has tested this extensively), Java 25 gets you the latest iteration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Java 25 is the realistic "upgrade from 21" target.&lt;/strong&gt; It's LTS. Every improvement from Java 22, 23, and 24 is included. For 1.21.x servers that want better performance without chasing the bleeding edge, Java 25 is the answer.&lt;/p&gt;

&lt;p&gt;Elevated&lt;/p&gt;

&lt;p&gt;Rather skip the Java juggling? Elevated game servers come set up with the right runtime for your Minecraft version.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/elevated/game-servers/" rel="noopener noreferrer"&gt;See Elevated game servers →&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What Java 26 Specifically Adds
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://openjdk.org/projects/jdk/26/" rel="noopener noreferrer"&gt;JDK 26&lt;/a&gt; is a short-term release. Six months of premier support after the March 17, 2026 release date. Not an LTS. If you run it on a production server, you need a plan to upgrade to Java 27 (or wait for whatever the next LTS is, which will be Java 29) within six months. That's real operational overhead.&lt;/p&gt;

&lt;p&gt;But let's talk about what it actually brings for servers, because this is the question:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;G1GC Synchronization Overhead Reduction&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/522" rel="noopener noreferrer"&gt;JEP 522&lt;/a&gt;). Java 26 reduces the amount of synchronization required between application threads and GC threads specifically in G1. This is a direct throughput improvement for the most common Minecraft server configuration. The &lt;a href="https://openjdk.org/jeps/522" rel="noopener noreferrer"&gt;JEP text&lt;/a&gt; frames it clearly: G1 performs more of its work concurrently with the application compared to throughput-oriented collectors like Parallel GC, but this concurrency requires coordination between your application threads and the GC threads, which both lowers throughput and adds latency.&lt;/p&gt;

&lt;p&gt;Java 26 reduces this synchronization overhead and shrinks the size of G1's injected write barrier code further. It builds directly on Java 24's late barrier expansion work. This means the write barriers that fire on every reference store in your game loop are slightly cheaper to execute. On a server doing hundreds of millions of reference stores per minute across entity updates, physics calculations, and redstone processing, "slightly cheaper" adds up to measurable sustained TPS improvement under load.&lt;/p&gt;

&lt;p&gt;This is the key point about Java 26's G1 improvements: &lt;strong&gt;you don't change your startup flags, you don't change your GC configuration, you just upgrade and G1GC gets faster.&lt;/strong&gt; That's the kind of improvement worth tracking.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AOT Object Caching — GC-Agnostic&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/516" rel="noopener noreferrer"&gt;JEP 516&lt;/a&gt;). Java 24 introduced the AOT cache. Java 25 extended it with method profiles. Java 26 makes it GC-agnostic. The previous implementation stored cached objects in GC-specific memory layouts, meaning if you built the AOT cache with G1, you couldn't use it with ZGC. Java 26 fixes this — cached objects are stored in a neutral format that any GC can load from. If you're running generational ZGC on Java 26 (which you should be if you have a large server), you can now also benefit from the full AOT cache. Previously these two optimizations were mutually exclusive. Java 26 removes that constraint.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Structured Concurrency — 6th Preview&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/525" rel="noopener noreferrer"&gt;JEP 525&lt;/a&gt;). Six preview cycles. It's not finalized but it's stable in practice. &lt;a href="https://papermc.io/software/folia/" rel="noopener noreferrer"&gt;Folia&lt;/a&gt; — the regionized multithreading fork of Paper — and future Paper async work can use structured concurrency primitives to write cleaner, safer parallel code. This doesn't impact you as a server admin today, but it's the language infrastructure that server software developers are building on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applet API Removal&lt;/strong&gt; (&lt;a href="https://openjdk.org/jeps/504" rel="noopener noreferrer"&gt;JEP 504&lt;/a&gt;). &lt;code&gt;java.applet&lt;/code&gt; is gone. This matters exactly zero to you as a Minecraft server admin, but it reduces JDK footprint slightly. Good riddance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Java 26 does NOT do for Minecraft servers:&lt;/strong&gt; It doesn't make the single-threaded tick loop multi-threaded. It doesn't eliminate GC pauses (though it reduces them). It doesn't make plugins faster. It doesn't fix whatever your &lt;code&gt;timings&lt;/code&gt; report says is eating 15ms per tick in your shop plugin.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Garbage Collector Decision
&lt;/h2&gt;

&lt;p&gt;Here's the uncomfortable truth: &lt;strong&gt;your GC choice has more impact on Minecraft server performance than the difference between Java 21 and Java 26.&lt;/strong&gt; Both decisions matter, but GC choice comes first.&lt;/p&gt;

&lt;h3&gt;
  
  
  G1GC with Aikar's Flags — Still The Right Default
&lt;/h3&gt;

&lt;p&gt;For most servers — under 100 players, 4-16GB heap allocated — &lt;a href="https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/" rel="noopener noreferrer"&gt;Aikar's G1GC flags&lt;/a&gt; are still the recommendation. They've been stress-tested in production for years on servers of every size and plugin stack. Use them:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java -Xms10G -Xmx10G \
  -XX:+UseG1GC \
  -XX:+ParallelRefProcEnabled \
  -XX:MaxGCPauseMillis=200 \
  -XX:+UnlockExperimentalVMOptions \
  -XX:+DisableExplicitGC \
  -XX:+AlwaysPreTouch \
  -XX:G1NewSizePercent=30 \
  -XX:G1MaxNewSizePercent=40 \
  -XX:G1HeapRegionSize=8M \
  -XX:G1ReservePercent=20 \
  -XX:G1HeapWastePercent=5 \
  -XX:G1MixedGCCountTarget=4 \
  -XX:InitiatingHeapOccupancyPercent=15 \
  -XX:G1MixedGCLiveThresholdPercent=90 \
  -XX:G1RSetUpdatingPauseTimePercent=5 \
  -XX:SurvivorRatio=32 \
  -XX:+PerfDisableSharedMem \
  -XX:MaxTenuringThreshold=1 \
  -Dusing.aikars.flags=https://mcflags.emc.gs \
  -Daikars.new.flags=true \
  -jar server.jar nogui
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;If you're on Java 25+, add these&lt;/strong&gt; — they're supported from Java 25 and Mojang considers them beneficial enough to include in their own default flags for future Minecraft versions:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  -XX:+UseCompactObjectHeaders \
  -XX:+UseStringDeduplication \
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The reason Aikar's flags tune G1 so heavily toward young generation is exactly what I explained earlier: Minecraft generates an extraordinary amount of short-lived objects. By giving G1 more young generation space (30-40% of heap), those objects die in cheap young GC collections instead of getting promoted to old generation where they're expensive to collect. The &lt;code&gt;MaxTenuringThreshold=1&lt;/code&gt; flag means objects that survive even one young GC get promoted immediately to old gen — this sounds counterintuitive but reduces the cost of survivor space processing for Minecraft's specific allocation patterns.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have more than 12GB allocated:&lt;/strong&gt; Adjust to &lt;code&gt;G1NewSizePercent=40&lt;/code&gt;, &lt;code&gt;G1MaxNewSizePercent=50&lt;/code&gt;, &lt;code&gt;G1HeapRegionSize=16M&lt;/code&gt;, &lt;code&gt;G1ReservePercent=15&lt;/code&gt;, &lt;code&gt;InitiatingHeapOccupancyPercent=20&lt;/code&gt;. Larger regions handle Minecraft's "humongous allocations" (objects larger than half the region size that go directly to old gen) more efficiently.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generational ZGC — The High-Player-Count Answer
&lt;/h3&gt;

&lt;p&gt;For servers running 100+ players with 16GB+ heap available, switch to Generational ZGC. The goal with ZGC is near-zero stop-the-world pause time. ZGC does almost all its work concurrently with your application. The tradeoff is it needs more RAM and more CPU cores to run those concurrent GC threads.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java -Xms16G -Xmx16G \
  -XX:+UseZGC \
  -XX:+ZGenerational \
  -XX:+AlwaysPreTouch \
  -XX:+DisableExplicitGC \
  -XX:+ParallelRefProcEnabled \
  -XX:+PerfDisableSharedMem \
  -XX:+UseCompactObjectHeaders \
  -XX:+UseStringDeduplication \
  -jar server.jar nogui
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;On Java 23+, &lt;code&gt;-XX:+ZGenerational&lt;/code&gt; is implied when you use &lt;code&gt;-XX:+UseZGC&lt;/code&gt;. On Java 25+, it's the only ZGC mode. Include the flag anyway for clarity in your startup script — future you will thank current you.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;ZGC Requirements that disqualify many setups&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;You need more RAM than G1GC — provision 20-25% more heap than you would with G1. If G1 works great at 8GB, ZGC needs 10-12GB to run well.&lt;/li&gt;
&lt;li&gt;You need more CPU cores — ZGC's concurrent threads need headroom. On a 2-core VPS, ZGC competes with your game simulation for CPU time and hurts you.&lt;/li&gt;
&lt;li&gt;ZGC is not available in Oracle's official JDK on all platforms. Use &lt;a href="https://adoptium.net/" rel="noopener noreferrer"&gt;Adoptium Temurin&lt;/a&gt; (wide availability, community-supported), &lt;a href="https://aws.amazon.com/corretto/" rel="noopener noreferrer"&gt;Amazon Corretto&lt;/a&gt; (production-ready), or the &lt;a href="https://learn.microsoft.com/en-us/java/openjdk/download" rel="noopener noreferrer"&gt;Microsoft Build of OpenJDK&lt;/a&gt; (Mojang's preferred distribution) to guarantee you have ZGC available.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The real-world case for ZGC&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;a href="https://cubxity.dev/blog/folia-test-june-2023" rel="noopener noreferrer"&gt;1,000-player Folia stress test documented by Cubxity&lt;/a&gt; used generational Shenandoah GC on Java 21 with a 100GB heap. At 600 players they measured 7.9GB/s heap allocation rate. At that scale, a GC that can do concurrent collection without stopping the world isn't nice to have — it's the difference between 20 TPS and an unplayable server.&lt;/p&gt;

&lt;h3&gt;
  
  
  What About Shenandoah?
&lt;/h3&gt;

&lt;p&gt;Shenandoah is another concurrent low-pause GC, available in Adoptium, Corretto, and Red Hat builds (not Oracle's JDK). The &lt;a href="https://github.com/brucethemoose/Minecraft-Performance-Flags-Benchmarks" rel="noopener noreferrer"&gt;brucethemoose benchmark research&lt;/a&gt; recommends Shenandoah for Minecraft clients but ZGC for powerful Java 17+ servers. The concern with Shenandoah on servers is that its concurrency model can compete more aggressively with your game simulation threads for CPU time than ZGC does. Generational Shenandoah (finalized in Java 25) is better than the non-generational version, but ZGC is generally better tested at high Minecraft server player counts.&lt;/p&gt;

&lt;p&gt;Try Shenandoah if you want to experiment. Use ZGC if you want the community-validated answer.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/minecraft-server-jar-guide/" rel="noopener noreferrer"&gt;Bukkit, Spigot, Paper, Folia: What You're Actually Running&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  The Server Software Matters Too
&lt;/h2&gt;

&lt;p&gt;I want to be honest with you about something. The performance difference between Java 21 and Java 26 is real but incremental. The performance difference between server software choices is massive.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Vanilla →&lt;/strong&gt;&lt;a href="https://papermc.io/" rel="noopener noreferrer"&gt;&lt;strong&gt;Paper&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; This is the biggest single performance improvement available to any Minecraft server admin, with zero Java version change. Paper implements dozens of micro-optimizations across entity AI, chunk loading, redstone, and mob spawning. It makes chunk loading asynchronous in ways vanilla doesn't. It fixes the algorithmic complexity of various vanilla systems. Paper on Java 21 beats vanilla Minecraft on Java 26 every time. It's a drop-in replacement for Spigot — if you're running vanilla or Spigot, just switch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Paper →&lt;/strong&gt;&lt;a href="https://purpurmc.org/" rel="noopener noreferrer"&gt;&lt;strong&gt;Purpur&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; Purpur is a Paper fork with additional configuration options and some extra patches. Not a dramatic performance difference but more control over things like entity behavior that can be tuned for your specific workload.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Paper →&lt;/strong&gt;&lt;a href="https://papermc.io/software/folia/" rel="noopener noreferrer"&gt;&lt;strong&gt;Folia&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;(for specific use cases):&lt;/strong&gt; Folia is Paper's experimental regionized multithreading fork, built by the same team. Instead of a single main thread ticking the entire world, &lt;a href="https://github.com/PaperMC/Folia" rel="noopener noreferrer"&gt;Folia divides the loaded world into independent regions that tick in parallel on a thread pool&lt;/a&gt;. For servers where players are spread out — SkyBlock, large SMP maps, anarchy servers — this can dramatically increase effective player capacity because multiple regions are ticking simultaneously. The &lt;a href="https://docs.papermc.io/folia/faq/" rel="noopener noreferrer"&gt;PaperMC documentation&lt;/a&gt; recommends at least 16 cores for Folia to be beneficial, and it breaks most plugins. It's not a drop-in replacement. But the ceiling it removes is real — the Cubxity 1,000-player stress test ran on Folia with generational Shenandoah on Java 21 and held 600 players at 20 TPS on consumer hardware.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Java version upgrade gets you incremental JVM improvements. Switching server software gets you architectural improvements. Do both, but understand the order of impact.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Profiling Actually Looks Like
&lt;/h2&gt;

&lt;p&gt;Every optimization conversation about Minecraft servers eventually comes down to this question: what is actually consuming your tick budget? You cannot optimize what you cannot measure, and guessing based on vibes is how you spend three hours tuning JVM flags that weren't your bottleneck.&lt;/p&gt;

&lt;p&gt;Install &lt;a href="https://spark.lucko.me/" rel="noopener noreferrer"&gt;Spark&lt;/a&gt;. It's a performance profiler built specifically for Minecraft servers. It integrates with Paper, Purpur, Folia, and others. Run these commands when your server is under load:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/spark profiler  # Identifies where tick time is being spent
/spark gcmonitor  # Shows GC pause frequency and duration in real time
/spark tps  # Shows current TPS and tick duration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;gcmonitor&lt;/code&gt; output will tell you immediately whether your GC is the problem. If you're seeing old generation collection pauses over 50ms, your GC configuration needs tuning before anything else. If you're seeing young generation pauses of 20-30ms every 2-3 seconds, you might need more heap or a different GC. If you're seeing no GC issues but low TPS, the profiler will tell you which plugins or game systems are eating your tick time.&lt;/p&gt;

&lt;p&gt;Enable GC logging in your startup flags to get a permanent record:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-Xlog:gc*:logs/gc.log:time,uptime,level,tags:filecount=5,filesize=20m
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This creates rotating log files in your server's &lt;code&gt;logs/&lt;/code&gt; directory. Any &lt;code&gt;Pause Full&lt;/code&gt; events in those logs are stop-the-world pauses — find them, understand what triggered them, and eliminate them.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Actual Decision Framework
&lt;/h2&gt;

&lt;p&gt;Alright. You've read the research. Here's what to actually do.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You're running 1.21.x on a stable server under 100 players&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Stay on Java 21 LTS unless something is broken. If you're having GC pause problems, fix your GC flags first. The gains from upgrading to 25 or 26 without also addressing GC configuration are modest.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You're running 1.21.x and want to future-proof&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Upgrade to Java 25 LTS. Not Java 22, 23, 24, or 26 — Java 25. It includes everything from the intermediate versions. It's LTS. Your plugins built for Java 21+ will run on it. Install &lt;a href="https://adoptium.net/en-GB/temurin/releases/?version=25" rel="noopener noreferrer"&gt;Adoptium Temurin 25&lt;/a&gt; or the &lt;a href="https://learn.microsoft.com/en-us/java/openjdk/download" rel="noopener noreferrer"&gt;Microsoft Build of OpenJDK 25&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You're running 100+ players and fighting GC pauses:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Switch to Generational ZGC on Java 21 or 25 before worrying about Java version. This is the highest-impact change available. Measure with &lt;code&gt;spark gcmonitor&lt;/code&gt; before and after.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You're planning for the future:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Java 26 is interesting for G1GC throughput and the GC-agnostic AOT cache. But it's a short-term release — six months of support. If you want the cutting edge without the operational overhead of tracking STR releases, wait: Java 29 will be the next LTS after Java 25, expected around September 2027. Java 26 right now is for people who want to test and benchmark, not for production deployments with no migration plan.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You're running Forge or Fabric mods&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Test everything before deploying. Mods interact with JVM internals more aggressively than plugins do. Java 25 is generally fine for modern mod loaders. Java 26 is less tested with the mod ecosystem as of today. Run a staging server with your full mod list before touching production.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;You want to skip Java 22 and 23 specifically:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Yes, skip them. They're both end-of-life. All their improvements are included in Java 24, 25, and 26. There's no reason to run them in production today.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Performance Impact Summary
&lt;/h2&gt;

&lt;p&gt;Here's the honest version of what you actually get, in terms relevant to a Minecraft server:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Java 21&lt;/th&gt;
&lt;th&gt;Java 22-23&lt;/th&gt;
&lt;th&gt;Java 24&lt;/th&gt;
&lt;th&gt;Java 25&lt;/th&gt;
&lt;th&gt;Java 26&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Generational ZGC&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅ Final&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅ Non-gen removed&lt;/td&gt;
&lt;td&gt;✅ Only mode&lt;/td&gt;
&lt;td&gt;✅ + AOT compatible&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;G1GC Write Barriers&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Baseline&lt;/td&gt;
&lt;td&gt;Early improvements&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Major improvement (-20% JIT work)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Extended&lt;/td&gt;
&lt;td&gt;Further reduced&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;AOT Cache&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅ Classes only&lt;/td&gt;
&lt;td&gt;✅ Classes + profiles&lt;/td&gt;
&lt;td&gt;✅ GC-agnostic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;C2 MergeStores (byte ops)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅ Extended&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Secondary Supertype Cache&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅ x64/AArch64&lt;/td&gt;
&lt;td&gt;✅ All platforms&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Auto-vectorization&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Baseline&lt;/td&gt;
&lt;td&gt;Minor&lt;/td&gt;
&lt;td&gt;Minor&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Major expansion&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Compact Object Headers&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;Preview&lt;/td&gt;
&lt;td&gt;✅ Stable&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;String hashCode folding&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Realistic TPS improvement from Java version upgrade alone (same server, same plugins, same GC):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java 21 → Java 25: Roughly 5-15% better sustained throughput on a loaded server. More noticeable on servers already running at high tick load (17-19 TPS) where any efficiency gain manifests as headroom.&lt;/li&gt;
&lt;li&gt;Java 21 → Java 26: Marginally better than 25. The G1GC synchronization reduction in 26 is real but not dramatic over 25.&lt;/li&gt;
&lt;li&gt;Java 21 → Java 25, &lt;strong&gt;also switching G1GC to Generational ZGC&lt;/strong&gt; with proper heap sizing on a 100+ player server: Much more significant — GC pause spikes that were making players rubber-band disappear. TPS stability improves substantially.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The honest truth is that no Java version upgrade is going to take a server that's drowning at 10 TPS to stable 20 TPS. If you're that far under the load ceiling, you have plugin problems or infrastructure problems. Java version is the last 5-15% of optimization, not the first.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Cncusion
&lt;/h2&gt;

&lt;p&gt;The question was: real-world performance gains from upgrading Java 21 → 22 → 23 → 26?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Java 22 and 23 specifically:&lt;/strong&gt; Short-term releases, already EOL. Real technical improvements landed in both, but you should not be running either in production in 2026. Skip them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Java 24:&lt;/strong&gt; G1GC JIT improvement is the most impactful Minecraft-relevant performance change in years. But it's also EOL. Included in 25.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Java 25:&lt;/strong&gt; The right upgrade target. LTS. Cumulative improvements from 22-24 plus its own additions. Generational ZGC is rock solid. AOT cache with method profiles speeds up server startup. Compact object headers reduce heap pressure. This is a genuinely better runtime than Java 21 for Minecraft.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Java 26:&lt;/strong&gt; The G1GC throughput improvement and GC-agnostic AOT cache are meaningful additions. But it's a short-term release with six months of support. Run it in staging, test it, benchmark it. Don't put it on production unless you're willing to track the upgrade cycle.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;GC configuration beats Java version.&lt;/strong&gt; If you're on Java 21 with poorly tuned G1GC flags, switching to Java 26 with the same broken flags doesn't help much. Fix the flags first. Or switch to generational ZGC if your player count warrants it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server software beats everything.&lt;/strong&gt; If you're on vanilla, switch to &lt;a href="https://papermc.io/" rel="noopener noreferrer"&gt;Paper&lt;/a&gt;. The &lt;a href="https://www.leafmc.one/docs/how-to/java-flags" rel="noopener noreferrer"&gt;Leaf documentation&lt;/a&gt;, the &lt;a href="https://github.com/brucethemoose/Minecraft-Performance-Flags-Benchmarks" rel="noopener noreferrer"&gt;brucethemoose benchmarks&lt;/a&gt;, and &lt;a href="https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/" rel="noopener noreferrer"&gt;Aikar's years of research&lt;/a&gt; all point at the same conclusion: the JVM optimizes running Paper better than running vanilla, your plugins are more isolated from the game loop, and async chunk loading alone is a larger throughput improvement than any Java version bump.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Measure everything.&lt;/strong&gt; Install &lt;a href="https://spark.lucko.me/" rel="noopener noreferrer"&gt;Spark&lt;/a&gt;. Run &lt;code&gt;/spark gcmonitor&lt;/code&gt; under real player load. Know what your actual GC pause pattern looks like before you change anything. Change one thing at a time. Measure again. The server admin community has been doing cargo-cult flag copying for years — don't be part of that.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Java ecosystem is genuinely moving faster than it has in a decade. &lt;a href="https://sudosecurity.org/java-26-new-features/" rel="noopener noreferrer"&gt;JDK 26's feature list&lt;/a&gt; reflects a JVM team that is shipping real engineering work in every release cycle. The cumulative impact from Java 21 to Java 25 is real and worth capturing — just do it on the LTS, not the STR.&lt;/p&gt;

&lt;p&gt;Related reading: &lt;a href="https://sudosecurity.org/minecraft-server-vps-hardening/" rel="noopener noreferrer"&gt;Hardening the Box: Minecraft Server Security Below the Game&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>minecraft</category>
      <category>java</category>
      <category>selfhosted</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Zero-Trust Access for Homelabbers: Teleport vs. Tailscale vs. WireGuard vs. Cloudflare Tunnel</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Fri, 20 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/zero-trust-access-for-homelabbers-teleport-vs-tailscale-vs-wireguard-vs-cloudflare-tunnel-5ab</link>
      <guid>https://dev.to/sudosecurity/zero-trust-access-for-homelabbers-teleport-vs-tailscale-vs-wireguard-vs-cloudflare-tunnel-5ab</guid>
      <description>&lt;p&gt;Every homelab remote-access thread eventually turns into the same four-way argument, and most of it happens because the four tools people are arguing about don't compete with each other. WireGuard is a protocol. Tailscale is a managed mesh network built on that protocol. Cloudflare Tunnel is a reverse proxy that publishes services to the public internet. Teleport is an identity-aware access broker that replaces SSH keys and audit-log spreadsheets. You can run all four in the same homelab without any of them stepping on each other, because they're solving different problems that all get marketed with the same "zero-trust" language.&lt;/p&gt;

&lt;p&gt;Here's what each one does, where each one breaks, and the combination that covers a real homelab.&lt;/p&gt;

&lt;h2&gt;
  
  
  WireGuard: the protocol everything else builds on
&lt;/h2&gt;

&lt;p&gt;WireGuard is a VPN protocol that landed in the mainline Linux kernel in version 5.6. It creates an encrypted point-to-point tunnel between two machines: generate a keypair, exchange public keys, set an &lt;code&gt;AllowedIPs&lt;/code&gt; range, done. No coordination server, no third party, no dependency on anyone but you.&lt;/p&gt;

&lt;p&gt;Raw WireGuard is the fastest option on the table, adding 1 to 3 milliseconds of latency for a direct connection, because there's no relay infrastructure between you and your server. It's also the least forgiving. You need a way in: a static IP, a DDNS setup, or a router that supports port forwarding. Every new device means generating a keypair and writing a config block by hand. If your ISP puts you behind CGNAT, which is increasingly common on residential connections and nearly universal on mobile carriers, raw WireGuard often can't establish a connection at all without a relay you'd have to run yourself.&lt;/p&gt;

&lt;p&gt;Run raw WireGuard when you have a small, mostly static set of devices, a reasonably stable network path in, and you want zero dependency on anyone else's infrastructure. Skip it if you're behind CGNAT or you're adding and removing devices often enough that hand-editing config files becomes the bottleneck.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tailscale: WireGuard with the coordination problem solved
&lt;/h2&gt;

&lt;p&gt;Tailscale runs the same WireGuard protocol underneath, but it manages the parts that make raw WireGuard painful: key distribution, NAT traversal, and DNS. Install the client, sign in, and your device appears on your private mesh network. No port forwarding, no manual key exchange, and it works through CGNAT because Tailscale's DERP relay network handles the handshake when a direct peer-to-peer connection isn't possible.&lt;/p&gt;

&lt;p&gt;The free tier covers up to 3 users and 100 devices, which is more than enough for a household or a single-operator homelab. For most connections between two WireGuard-capable devices, Tailscale negotiates a direct connection and the relay only kicks in as fallback, so the latency penalty over raw WireGuard is usually small, typically 5 to 15 milliseconds. The trade-off is architectural: your coordination plane runs on Tailscale's infrastructure. If Tailscale's control servers go down, existing connections keep working, but new devices can't join the network until service is restored. Headscale, an open-source reimplementation of Tailscale's control server, removes that dependency if you're willing to self-host and maintain it yourself.&lt;/p&gt;

&lt;p&gt;Run Tailscale when you want private, device-to-device access without touching your router, especially if you're behind CGNAT or managing more than a couple of devices. It's the right default for most homelabbers who aren't already committed to a self-hosted-everything philosophy.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/sso-tax-self-hosted-login-paywall/" rel="noopener noreferrer"&gt;The SSO Tax: Why Self-Hosted Projects Are Gating Login Behind a Paywall&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Cloudflare Tunnel: not a VPN, a one-way publishing tool
&lt;/h2&gt;

&lt;p&gt;This is where the comparisons usually get muddled. Cloudflare Tunnel doesn't build a private network between devices at all. It runs &lt;code&gt;cloudflared&lt;/code&gt;, a small agent, on your homelab machine, which opens an outbound connection to Cloudflare's edge and publishes a specific service through it. Cloudflare assigns a public URL, terminates TLS at their edge, and routes incoming requests to your service. No inbound ports opened on your router, ever.&lt;/p&gt;

&lt;p&gt;That makes it excellent for exactly one use case: putting a web app in front of people who shouldn't need a VPN client to reach it, non-technical family members checking your Immich photo library, for instance, or an app you want indexed and reachable from anywhere without asking anyone to install anything. It is a poor substitute for private network access. It doesn't give you SSH, SMB, RDP, or arbitrary TCP/UDP connectivity, only HTTP/HTTPS services get published cleanly, and your traffic terminates on Cloudflare's infrastructure before it reaches your server, which is a real trust boundary to weigh if that matters for your threat model.&lt;/p&gt;

&lt;p&gt;Run Cloudflare Tunnel for the specific web apps you want to publish to the open internet. Don't reach for it as your primary remote-access method for admin tasks; pair it with Tailscale or WireGuard for that instead.&lt;/p&gt;

&lt;p&gt;Sidechannel&lt;/p&gt;

&lt;p&gt;Locked down the network? Do the same for your conversations. Sidechannel is SudoSecurity's end-to-end encrypted chat.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/sidechannel/" rel="noopener noreferrer"&gt;See Sidechannel →&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Teleport: the one built for accountability, not only access
&lt;/h2&gt;

&lt;p&gt;Teleport solves a different problem than the other three: not "how do I connect," but "who did what, and can I prove it." It replaces SSH key sprawl with short-lived certificates issued after identity verification, and it logs every SSH session, database query, and Kubernetes command as a structured, replayable audit event. If you've ever needed to answer "who ran that command on the production box last Tuesday," that's Teleport's actual job.&lt;/p&gt;

&lt;p&gt;For a homelab, this is heavier than most setups need, and there's a licensing wrinkle worth knowing before you build around it. Starting with Teleport 16, the Community Edition license changed: it's now self-certified as free only for individuals and organizations under 100 employees and under $10 million in annual revenue, and several features homelabbers relied on, including some SSO integrations, moved behind the paid Enterprise tier. That's drawn real frustration in the self-hosting community, with some early adopters describing it as a bait-and-switch after building workflows around what they understood to be a permanently open-source tool. For a solo homelabber, the free-tier terms are unlikely to bind you in practice, but it's worth reading Teleport's own community license post before you standardize your entire infrastructure access model on it, the same due diligence worth applying to any self-hosted tool that's quietly narrowed its free tier before.&lt;/p&gt;

&lt;p&gt;Run Teleport if you're managing SSH, database, or Kubernetes access across a handful of machines and want real audit trails, especially if other people (family, friends contributing to a project) need scoped access without you handing out your actual credentials. Skip it if you're the only person touching your homelab and a simple VPN answers every question you have.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Tool&lt;/th&gt;
&lt;th&gt;Solves&lt;/th&gt;
&lt;th&gt;Free tier ceiling&lt;/th&gt;
&lt;th&gt;Best fit&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;WireGuard&lt;/td&gt;
&lt;td&gt;Point-to-point encrypted tunnel&lt;/td&gt;
&lt;td&gt;Unlimited, self-managed&lt;/td&gt;
&lt;td&gt;Small, static device set, no CGNAT&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Tailscale&lt;/td&gt;
&lt;td&gt;Managed mesh, zero-config NAT traversal&lt;/td&gt;
&lt;td&gt;3 users, 100 devices&lt;/td&gt;
&lt;td&gt;Most homelabs behind CGNAT&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cloudflare Tunnel&lt;/td&gt;
&lt;td&gt;Publish a web app publicly&lt;/td&gt;
&lt;td&gt;Generous, no device cap&lt;/td&gt;
&lt;td&gt;Sharing specific apps with non-technical users&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Teleport&lt;/td&gt;
&lt;td&gt;Identity-aware access + audit logging&lt;/td&gt;
&lt;td&gt;Free, but license narrowed since v16&lt;/td&gt;
&lt;td&gt;Multi-user access with accountability needs&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  The combination that covers a homelab
&lt;/h2&gt;

&lt;p&gt;The pattern that shows up repeatedly in real homelab setups, and the one I'd recommend starting from: Tailscale (or raw WireGuard if you're not behind CGNAT and want zero third-party dependency) for private admin access to everything, SSH, Proxmox, your NAS, internal dashboards, plus Cloudflare Tunnel layered on top for the one or two services you deliberately want public. If you're already running a &lt;a href="https://sudosecurity.org/self-hosted-productivity-stack-nextcloud-vaultwarden-immich-jellyfin-paperless-2026/" rel="noopener noreferrer"&gt;self-hosted productivity stack&lt;/a&gt;, that's Tailscale for reaching Vaultwarden and your admin panels, Cloudflare Tunnel for the Immich instance you want grandma to open from a browser link.&lt;/p&gt;

&lt;p&gt;Add Teleport into that stack only once you've got more than one person touching production-adjacent infrastructure, or you're managing enough machines that "which SSH key did I put on which box" has become a real question instead of a hypothetical one. I've written up the &lt;a href="https://sudosecurity.org/teleport-self-hosted-zero-trust-infrastructure-access-complete-guide-2026/" rel="noopener noreferrer"&gt;full Teleport self-hosted setup&lt;/a&gt; separately if you land there; it's worth the deployment effort for the audit trail alone once you cross that threshold.&lt;/p&gt;

&lt;p&gt;None of these four tools is wrong. They answer different questions, and picking the wrong one for your question is how you end up publishing your SSH port to the internet through a tool that was built to publish a web app, or fighting CGNAT with a protocol that has no answer for it.&lt;/p&gt;

&lt;p&gt;Related reading: &lt;a href="https://sudosecurity.org/inside-of-cloudflare-os/" rel="noopener noreferrer"&gt;Cloudflare OS: Inside the Open-Source Agent Sandbox&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>security</category>
      <category>selfhosted</category>
      <category>networking</category>
      <category>zerotrust</category>
    </item>
    <item>
      <title>Self-Hosted Email in 2026: Mailcow vs Mailu vs Stalwart — Which Mail Server Should You Trust?</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Thu, 19 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/self-hosted-email-in-2026-mailcow-vs-mailu-vs-stalwart-which-mail-server-should-you-trust-21l</link>
      <guid>https://dev.to/sudosecurity/self-hosted-email-in-2026-mailcow-vs-mailu-vs-stalwart-which-mail-server-should-you-trust-21l</guid>
      <description>&lt;h2&gt;
  
  
  Self-Hosted Email Isn't Dead—It's Growing Up
&lt;/h2&gt;

&lt;p&gt;Imagine owning your own house versus renting an apartment.&lt;/p&gt;

&lt;p&gt;When you rent, someone else decides the rules, raises the rent, and can even lock certain doors.&lt;/p&gt;

&lt;p&gt;Owning your own house requires maintenance—but you control everything.&lt;/p&gt;

&lt;p&gt;Email works the same way.&lt;/p&gt;

&lt;p&gt;For decades, businesses outsourced communication to cloud providers like Microsoft 365 and Google Workspace because running an email server was considered difficult, unreliable, and expensive.&lt;/p&gt;

&lt;p&gt;In 2026, that narrative is beginning to change.&lt;/p&gt;

&lt;p&gt;Modern open-source mail platforms have dramatically simplified deployment through containers, automation, and improved security tooling. Meanwhile, growing concerns about data sovereignty, AI privacy, compliance regulations, and rising SaaS costs are motivating developers, startups, and even small businesses to reconsider self-hosted infrastructure.&lt;/p&gt;

&lt;p&gt;The real question is no longer:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"Can you self-host email?"&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It's:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;"Which platform fits your needs?"&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Among today's strongest contenders are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mailcow&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mailu&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stalwart&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each takes a fundamentally different engineering approach to solving the same problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Self-Hosted Email (Without the Jargon)
&lt;/h2&gt;

&lt;p&gt;Think of email like a modern postal system.&lt;/p&gt;

&lt;p&gt;Instead of letters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SMTP becomes the delivery truck.&lt;/li&gt;
&lt;li&gt;IMAP becomes your mailbox.&lt;/li&gt;
&lt;li&gt;Spam filters become customs officers.&lt;/li&gt;
&lt;li&gt;DNS records become the postal address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Commercial email providers operate enormous centralized post offices.&lt;/p&gt;

&lt;p&gt;A self-hosted server builds your own.&lt;/p&gt;

&lt;p&gt;That means you become responsible for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;accepting incoming mail,&lt;/li&gt;
&lt;li&gt;delivering outgoing mail,&lt;/li&gt;
&lt;li&gt;preventing spam,&lt;/li&gt;
&lt;li&gt;securing communication,&lt;/li&gt;
&lt;li&gt;maintaining reputation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Modern projects automate most of these responsibilities—but they automate them differently.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three Different Engineering Philosophies
&lt;/h2&gt;

&lt;p&gt;Rather than competing only on features, Mailcow, Mailu, and Stalwart represent three different architectural philosophies.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mailcow: The Enterprise Toolkit
&lt;/h3&gt;

&lt;p&gt;Mailcow is best viewed as a carefully assembled ecosystem.&lt;/p&gt;

&lt;p&gt;Instead of reinventing email infrastructure, it combines mature open-source components such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SMTP server&lt;/li&gt;
&lt;li&gt;IMAP server&lt;/li&gt;
&lt;li&gt;Spam filtering&lt;/li&gt;
&lt;li&gt;Antivirus scanning&lt;/li&gt;
&lt;li&gt;Webmail&lt;/li&gt;
&lt;li&gt;Calendar&lt;/li&gt;
&lt;li&gt;Contacts&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;into one Docker-managed platform.&lt;/p&gt;

&lt;p&gt;Think of it as building a Formula One car from world-class parts.&lt;/p&gt;

&lt;p&gt;Every component specializes in one task.&lt;/p&gt;

&lt;p&gt;The benefit?&lt;/p&gt;

&lt;p&gt;Exceptional flexibility and years of production maturity.&lt;/p&gt;

&lt;p&gt;The trade-off?&lt;/p&gt;

&lt;p&gt;Higher resource usage and operational complexity.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mailu: The Balanced Platform
&lt;/h3&gt;

&lt;p&gt;Mailu takes many of the same building blocks but focuses on simplicity.&lt;/p&gt;

&lt;p&gt;Configuration is cleaner.&lt;/p&gt;

&lt;p&gt;Deployment requires fewer manual decisions.&lt;/p&gt;

&lt;p&gt;Updates generally feel less intimidating for newcomers.&lt;/p&gt;

&lt;p&gt;Imagine buying a well-designed modular workstation instead of assembling individual components yourself.&lt;/p&gt;

&lt;p&gt;You sacrifice a little flexibility but gain usability.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/self-hosted-email-server-mailcow-setup-guide-2026/" rel="noopener noreferrer"&gt;How to Self-Host Your Own Email Server With Mailcow in 2026 — Complete Setup Guide&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  Stalwart: Reinventing the Mail Server
&lt;/h3&gt;

&lt;p&gt;Stalwart approaches the problem differently.&lt;/p&gt;

&lt;p&gt;Rather than orchestrating numerous independent services, it implements core functionality within a single Rust-based application.&lt;/p&gt;

&lt;p&gt;It's similar to replacing an entire workshop full of specialized machines with one advanced manufacturing robot.&lt;/p&gt;

&lt;p&gt;Advantages include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;fewer moving parts&lt;/li&gt;
&lt;li&gt;lower memory consumption&lt;/li&gt;
&lt;li&gt;simpler deployment&lt;/li&gt;
&lt;li&gt;reduced operational overhead&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Its architecture also enables native support for modern protocols such as &lt;strong&gt;JMAP&lt;/strong&gt; , positioning it for future email applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Engineering Trade-Offs That Actually Matter
&lt;/h2&gt;

&lt;p&gt;Choosing an email server isn't about finding the "best."&lt;/p&gt;

&lt;p&gt;It's about choosing the right compromises.&lt;/p&gt;

&lt;h3&gt;
  
  
  Resource Consumption
&lt;/h3&gt;

&lt;p&gt;Mailcow provides the richest feature set but consumes considerably more RAM and CPU because multiple independent services run simultaneously.&lt;/p&gt;

&lt;p&gt;Mailu offers a lighter footprint while preserving most enterprise capabilities.&lt;/p&gt;

&lt;p&gt;Stalwart is optimized for efficiency and can comfortably operate on significantly smaller virtual machines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trade-off:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Higher functionality often means higher infrastructure costs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Operational Complexity
&lt;/h3&gt;

&lt;p&gt;Mailcow rewards administrators who enjoy customization.&lt;/p&gt;

&lt;p&gt;Mailu reduces complexity without hiding important controls.&lt;/p&gt;

&lt;p&gt;Stalwart minimizes operational burden by consolidating functionality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trade-off:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Flexibility versus simplicity.&lt;/p&gt;

&lt;h3&gt;
  
  
  Security
&lt;/h3&gt;

&lt;p&gt;All three support:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;TLS&lt;/li&gt;
&lt;li&gt;SPF&lt;/li&gt;
&lt;li&gt;DKIM&lt;/li&gt;
&lt;li&gt;DMARC&lt;/li&gt;
&lt;li&gt;encrypted authentication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mailcow benefits from years of community hardening.&lt;/p&gt;

&lt;p&gt;Mailu inherits stability from mature components.&lt;/p&gt;

&lt;p&gt;Stalwart benefits from Rust's memory safety, reducing entire categories of software vulnerabilities.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scalability
&lt;/h3&gt;

&lt;p&gt;Mailcow remains attractive for organizations requiring:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;multiple domains&lt;/li&gt;
&lt;li&gt;shared calendars&lt;/li&gt;
&lt;li&gt;collaborative workflows&lt;/li&gt;
&lt;li&gt;advanced administration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mailu scales comfortably for families and small businesses.&lt;/p&gt;

&lt;p&gt;Stalwart currently excels in modern deployments emphasizing operational simplicity.&lt;/p&gt;

&lt;p&gt;Sidechannel&lt;/p&gt;

&lt;p&gt;Some conversations shouldn't go over email at all. Sidechannel is SudoSecurity's end-to-end encrypted chat.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/sidechannel/" rel="noopener noreferrer"&gt;See Sidechannel →&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Where Self-Hosted Email Is Being Used
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Remote Work
&lt;/h3&gt;

&lt;p&gt;Organizations seeking complete ownership over communication infrastructure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Healthcare
&lt;/h3&gt;

&lt;p&gt;Hospitals protecting sensitive patient communication under strict privacy regulations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Legal Firms
&lt;/h3&gt;

&lt;p&gt;Maintaining document confidentiality while avoiding third-party dependency.&lt;/p&gt;

&lt;h3&gt;
  
  
  Universities
&lt;/h3&gt;

&lt;p&gt;Hosting thousands of institutional mailboxes with complete administrative control.&lt;/p&gt;

&lt;h3&gt;
  
  
  Aviation
&lt;/h3&gt;

&lt;p&gt;Supporting internal operational messaging within isolated infrastructure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Research Laboratories
&lt;/h3&gt;

&lt;p&gt;Protecting intellectual property from unnecessary cloud exposure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Privacy-Focused Startups
&lt;/h3&gt;

&lt;p&gt;Building products where customer trust depends on infrastructure transparency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mailcow vs Mailu vs Stalwart
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Mailcow&lt;/th&gt;
&lt;th&gt;Mailu&lt;/th&gt;
&lt;th&gt;Stalwart&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Learning Curve&lt;/td&gt;
&lt;td&gt;Medium–High&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Resource Usage&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;td&gt;Moderate&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Deployment&lt;/td&gt;
&lt;td&gt;Docker&lt;/td&gt;
&lt;td&gt;Docker&lt;/td&gt;
&lt;td&gt;Single service&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Web Interface&lt;/td&gt;
&lt;td&gt;Excellent&lt;/td&gt;
&lt;td&gt;Good&lt;/td&gt;
&lt;td&gt;Modern&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Collaboration Features&lt;/td&gt;
&lt;td&gt;Excellent&lt;/td&gt;
&lt;td&gt;Limited&lt;/td&gt;
&lt;td&gt;Growing&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance&lt;/td&gt;
&lt;td&gt;Very Good&lt;/td&gt;
&lt;td&gt;Very Good&lt;/td&gt;
&lt;td&gt;Excellent&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Modern Protocols&lt;/td&gt;
&lt;td&gt;Standard&lt;/td&gt;
&lt;td&gt;Standard&lt;/td&gt;
&lt;td&gt;Includes JMAP&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Community Size&lt;/td&gt;
&lt;td&gt;Large&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;td&gt;Growing&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Enterprise Readiness&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;td&gt;Emerging&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best For&lt;/td&gt;
&lt;td&gt;Teams &amp;amp; businesses&lt;/td&gt;
&lt;td&gt;Families &amp;amp; SMBs&lt;/td&gt;
&lt;td&gt;Modern greenfield deployments&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Deliverability: The Real Challenge
&lt;/h2&gt;

&lt;p&gt;Ironically, choosing software is often the easiest part.&lt;/p&gt;

&lt;p&gt;The biggest determinant of email success remains &lt;strong&gt;reputation&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Major providers increasingly rely on machine learning systems to evaluate:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;IP reputation&lt;/li&gt;
&lt;li&gt;authentication records&lt;/li&gt;
&lt;li&gt;sending behavior&lt;/li&gt;
&lt;li&gt;historical trust&lt;/li&gt;
&lt;li&gt;domain consistency&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Even the most sophisticated mail server cannot compensate for poor operational practices.&lt;/p&gt;

&lt;p&gt;Successful deployments prioritize:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;correct DNS configuration&lt;/li&gt;
&lt;li&gt;gradual reputation building&lt;/li&gt;
&lt;li&gt;secure authentication&lt;/li&gt;
&lt;li&gt;responsible sending behavior&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Infrastructure matters.&lt;/p&gt;

&lt;p&gt;Reputation matters more.&lt;/p&gt;

&lt;h2&gt;
  
  
  How AI Will Change Self-Hosted Email (2026–2031)
&lt;/h2&gt;

&lt;p&gt;Artificial intelligence is poised to transform mail administration.&lt;/p&gt;

&lt;p&gt;Expect future platforms to include:&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/what-self-hosters-are-ripping-out-of-their-stacks-in-2026/" rel="noopener noreferrer"&gt;What Self-Hosters Are Ripping Out of Their Stacks in 2026&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  AI Spam Detection
&lt;/h3&gt;

&lt;p&gt;Adaptive models continuously learning from organizational communication patterns.&lt;/p&gt;

&lt;h3&gt;
  
  
  AI Configuration Assistants
&lt;/h3&gt;

&lt;p&gt;Administrators will receive natural-language guidance instead of searching documentation.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Your DKIM configuration may reduce Gmail trust. Here's how to fix it."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Autonomous Maintenance
&lt;/h3&gt;

&lt;p&gt;Agentic AI systems may automatically:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;renew certificates&lt;/li&gt;
&lt;li&gt;monitor reputation&lt;/li&gt;
&lt;li&gt;optimize mail queues&lt;/li&gt;
&lt;li&gt;detect abuse&lt;/li&gt;
&lt;li&gt;recommend infrastructure improvements&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Predictive Deliverability
&lt;/h3&gt;

&lt;p&gt;Rather than discovering delivery failures afterward, AI could forecast reputation issues before messages are sent.&lt;/p&gt;

&lt;h3&gt;
  
  
  Intelligent Security
&lt;/h3&gt;

&lt;p&gt;Future systems may identify:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;phishing campaigns&lt;/li&gt;
&lt;li&gt;compromised accounts&lt;/li&gt;
&lt;li&gt;unusual login behavior&lt;/li&gt;
&lt;li&gt;anomalous outbound traffic&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;before administrators even notice them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which Platform Should You Choose?
&lt;/h2&gt;

&lt;p&gt;Choose &lt;strong&gt;Mailcow&lt;/strong&gt; if you want enterprise-grade collaboration, mature tooling, and extensive administrative capabilities.&lt;/p&gt;

&lt;p&gt;docker-compose.yml&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Mailcow is NOT configured via a hand-rolled Compose file.
# Use the official installer:
#   git clone https://github.com/mailcow/mailcow-dockerized
#   cd mailcow-dockerized
#   ./generate_config.sh
# It produces mailcow.conf and docker-compose.yml for you.
# Minimum specs: 4 vCPU, 6 GB RAM, 20 GB disk.
# Below is a simplified excerpt showing the network shape:

services:
  postfix-mailcow:
    image: mailcow/postfix:latest
    restart: always
    ports:
      - "25:25"
      - "587:587"
      - "465:465"
    networks:
      - mailcow-network

  dovecot-mailcow:
    image: mailcow/dovecot:latest
    restart: always
    ports:
      - "993:993"
      - "995:995"
      - "143:143"
    networks:
      - mailcow-network

  rspamd-mailcow:
    image: mailcow/rspamd:latest
    restart: always
    networks:
      - mailcow-network

networks:
  mailcow-network:
    driver: bridge
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Choose &lt;strong&gt;Mailu&lt;/strong&gt; if you value balance between simplicity and functionality while keeping resource usage moderate.&lt;/p&gt;

&lt;p&gt;docker-compose.yml&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generated by https://setup.mailu.io — example excerpt.
# Full setup: visit setup.mailu.io, fill in your domain/config, download.

services:
  front:
    image: ghcr.io/mailu/nginx:2024.06
    restart: always
    ports:
      - "25:25"
      - "465:465"
      - "587:587"
      - "993:993"
    volumes:
      - "/mailu/certs:/certs"
      - "/mailu/overrides/nginx:/overrides:ro"

  imap:
    image: ghcr.io/mailu/dovecot:2024.06
    restart: always
    volumes:
      - "/mailu/mail:/mail"
      - "/mailu/overrides/dovecot:/overrides:ro"

  smtp:
    image: ghcr.io/mailu/postfix:2024.06
    restart: always
    volumes:
      - "/mailu/mailqueue:/queue"

  antispam:
    image: ghcr.io/mailu/rspamd:2024.06
    restart: always

  webmail:
    image: ghcr.io/mailu/webmail:2024.06
    restart: always 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Choose &lt;strong&gt;Stalwart&lt;/strong&gt; if you're starting a new deployment and prefer a lightweight, modern architecture with an eye toward future protocols and operational efficiency.&lt;/p&gt;

&lt;p&gt;docker-compose.yml&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services:
  stalwart:
    image: stalwartlabs/mail-server:latest
    restart: always
    ports:
      - "25:25"
      - "465:465"
      - "587:587"
      - "993:993"
      - "143:143"
      - "4190:4190"   # ManageSieve
      - "8080:8080"   # Admin UI
    volumes:
      - stalwart-data:/opt/stalwart-mail
    environment:
      - TZ=UTC

volumes:
  stalwart-data:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There isn't a universal winner.&lt;/p&gt;

&lt;p&gt;There is only the platform that best matches your team's skills, infrastructure budget, and long-term strategy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Self-hosting email in 2026 is no longer an experiment reserved for Linux enthusiasts.&lt;/p&gt;

&lt;p&gt;It's becoming a strategic infrastructure decision.&lt;/p&gt;

&lt;p&gt;As organizations place greater emphasis on privacy, sovereignty, compliance, and AI-aware workflows, owning communication infrastructure becomes increasingly attractive.&lt;/p&gt;

&lt;p&gt;Whether you choose the maturity of Mailcow, the balance of Mailu, or the modern architecture of Stalwart, success ultimately depends less on software and more on disciplined operations, sound security practices, and thoughtful system administration.&lt;/p&gt;

&lt;p&gt;The future of work isn't just about using smarter tools.&lt;/p&gt;

&lt;p&gt;It's about understanding the infrastructure that powers them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Mailcow&lt;/strong&gt; excels for feature-rich, collaborative deployments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mailu&lt;/strong&gt; balances usability with resource efficiency.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stalwart&lt;/strong&gt; embraces a modern, streamlined architecture with strong potential for the future.&lt;/li&gt;
&lt;li&gt;Deliverability depends on operational excellence as much as software choice.&lt;/li&gt;
&lt;li&gt;AI is likely to make self-hosted email increasingly autonomous, secure, and accessible.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Join the Conversation
&lt;/h3&gt;

&lt;p&gt;Have you deployed &lt;strong&gt;Mailcow&lt;/strong&gt; , &lt;strong&gt;Mailu&lt;/strong&gt; , or &lt;strong&gt;Stalwart&lt;/strong&gt; in production?&lt;/p&gt;

&lt;p&gt;Share your experience, lessons learned, and favorite features in the comments. Your insights could help others make an informed decision as self-hosted email continues to evolve.&lt;/p&gt;

</description>
      <category>selfhosted</category>
      <category>email</category>
      <category>devops</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Self-Hosting Vaultwarden Without Trusting the Defaults</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Wed, 18 Nov 2026 14:00:01 +0000</pubDate>
      <link>https://dev.to/sudosecurity/self-hosting-vaultwarden-without-trusting-the-defaults-4j3</link>
      <guid>https://dev.to/sudosecurity/self-hosting-vaultwarden-without-trusting-the-defaults-4j3</guid>
      <description>&lt;p&gt;Somebody with your email address and your reused password is trying it against forty sites right now. That is not a scare story, it is the business model of every &lt;a href="https://sudosecurity.org/what-is-infostealer/" rel="noopener noreferrer"&gt;infostealer&lt;/a&gt; log ever sold. A password manager is the only practical answer, and running your own means the vault ciphertext lives on hardware you can put your hands on.&lt;/p&gt;

&lt;p&gt;It also means you are now the one who gets paged. Here is the whole server:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /opt/vaultwarden/docker-compose.yml
services:
  vaultwarden:
    image: vaultwarden/server:1.37.5
    container_name: vaultwarden
    restart: unless-stopped
    environment:
      DOMAIN: "https://vault.example.com"
      SIGNUPS_ALLOWED: "false"
      INVITATIONS_ALLOWED: "true"
      ADMIN_TOKEN: '$$argon2id$$v=19$$m=65540,t=3,p=4$$SALT$$HASH'
    volumes:
      - ./data:/data
    ports:
      - "127.0.0.1:8080:80"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it. One container, one volume, four environment variables. It'll work.&lt;/p&gt;

&lt;p&gt;This is week one of Self Hosting Saturday, and Vaultwarden is the right place to start, because it is the service people most reliably set up once and then stop thinking about for a year. It is also the one holding every other credential you own. Everything below is checked against the source at tag &lt;code&gt;1.37.5&lt;/code&gt;, AGPL-3.0, released 1 November 2026 — not against what the settings sound like they do.&lt;/p&gt;

&lt;h2&gt;
  
  
  What You Are Actually Installing
&lt;/h2&gt;

&lt;p&gt;Vaultwarden is not Bitwarden. It is an independent server written in &lt;a href="https://sudosecurity.org/what-is-rust/" rel="noopener noreferrer"&gt;Rust&lt;/a&gt;, started by Daniel García (&lt;code&gt;dani-garcia&lt;/code&gt;), with Mathijs van Veluw (&lt;code&gt;BlackDex&lt;/code&gt;) cutting a good share of recent releases, and it implements Bitwarden's client API. The official Bitwarden clients — browser extension, desktop, iOS, Android, CLI — talk to it without modification or patching. They don't know the difference.&lt;/p&gt;

&lt;p&gt;What you gain is footprint, though less than the usual comparison claims. Bitwarden's standard self-hosted deployment is eleven containers — their own blog says so — and every deployment except one ships an MSSQL Express image by default. That is the version of this argument everybody repeats. It stopped being the whole picture in December 2025, when Bitwarden Lite (previously "unified") went generally available as a single container that will talk to SQLite, PostgreSQL, MySQL or MSSQL. If container count is your objection, Bitwarden has an answer to it now.&lt;/p&gt;

&lt;p&gt;What is still true is the shape of the thing. Vaultwarden is one static binary plus the compiled web vault on &lt;code&gt;debian:trixie-slim&lt;/code&gt;, defaulting to SQLite, with no licence server in the path and no feature gates. Bitwarden's own documentation positions Lite for personal use and home labs rather than business deployments. Pick on the merits, not on a container count from 2022.&lt;/p&gt;

&lt;p&gt;What you inherit is the version treadmill, and it now runs in both directions. Vaultwarden trails the clients — 1.37.0's notes require it for clients at 2026.7.0 or newer, 1.37.2's for 2026.8.0 — and it has also started dropping support behind itself. 1.37.4 broke &lt;code&gt;bw send receive&lt;/code&gt; on CLI 2026.4.2 and older, and removed the legacy &lt;code&gt;POST /identity/accounts/register&lt;/code&gt; and &lt;code&gt;POST /api/accounts/prelogin&lt;/code&gt; endpoints outright. 1.37.5 is required before web vault 2026.7.1 and newer can toggle two-step login methods at all, and before 2026.9.0 and newer can take over an account through emergency access.&lt;/p&gt;

&lt;p&gt;Your phone auto-updates. Your server doesn't. Hold the server back far enough and features start failing in the client with no error that points at the server.&lt;/p&gt;

&lt;p&gt;One thing worth being clear about, because guides gloss it: the encryption is not Vaultwarden's. Vault items are encrypted and decrypted in the client, with a key derived from your master password, and the server stores ciphertext it cannot read. Compromising the server doesn't hand over your passwords. It hands over encrypted blobs, metadata, and whatever an attacker can do with admin access — which, as the advisory list further down shows, is not nothing.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Compose File, With the Dead Options Removed
&lt;/h2&gt;

&lt;p&gt;Search for a Vaultwarden compose file and roughly half of what you find still contains this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      WEBSOCKET_ENABLED: "true"
      WEBSOCKET_PORT: 3012
    ports:
      - "3012:3012"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Delete all of it. The separate WebSocket server was folded into the main Rocket process in 1.30.0 and the standalone port was removed outright in 1.31.0. &lt;code&gt;WEBSOCKET_PORT&lt;/code&gt; doesn't exist any more. The Dockerfile at 1.37.5 declares exactly one port:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VOLUME /data
EXPOSE 80
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Real-time sync now lives on the same port as everything else, at &lt;code&gt;/notifications/hub&lt;/code&gt; and &lt;code&gt;/notifications/anonymous-hub&lt;/code&gt;, both mounted under the &lt;code&gt;/notifications&lt;/code&gt; prefix in &lt;code&gt;src/main.rs&lt;/code&gt;. &lt;code&gt;ENABLE_WEBSOCKET&lt;/code&gt; defaults to &lt;code&gt;true&lt;/code&gt; and there's no reason to touch it.&lt;/p&gt;

&lt;p&gt;Here is the version worth typing, expanded from the four-variable stub above:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /opt/vaultwarden/docker-compose.yml
services:
  vaultwarden:
    image: vaultwarden/server:1.37.5
    container_name: vaultwarden
    restart: unless-stopped
    environment:
      DOMAIN: "https://vault.example.com"

      # Registration: closed, invite-only. Read the whitelist section below
      # before you add SIGNUPS_DOMAINS_WHITELIST to this block.
      SIGNUPS_ALLOWED: "false"
      INVITATIONS_ALLOWED: "true"
      SIGNUPS_VERIFY: "true"

      # Nobody but you creates organisations.
      ORG_CREATION_USERS: "none"

      # Audit logging for orgs is off by default. Turn it on, and set a
      # retention window or the cleanup job never starts.
      ORG_EVENTS_ENABLED: "true"
      EVENTS_DAYS_RETAIN: "90"

      # No password hints on a public instance.
      PASSWORD_HINTS_ALLOWED: "false"

      ADMIN_TOKEN: '$$argon2id$$v=19$$m=65540,t=3,p=4$$SALT$$HASH'

    volumes:
      - ./data:/data
    ports:
      # Bound to loopback. The reverse proxy is the only thing that reaches it.
      - "127.0.0.1:8080:80"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note what is absent. No &lt;code&gt;LOGIN_RATELIMIT_*&lt;/code&gt;, because the defaults are already correct and writing them out invites getting them wrong. That section is further down, and it is the one most guides break.&lt;/p&gt;

&lt;h2&gt;
  
  
  HTTPS Is Not a Recommendation Here
&lt;/h2&gt;

&lt;p&gt;You need HTTPS, and it is worth knowing that two separate mechanisms enforce that, because they fail differently.&lt;/p&gt;

&lt;p&gt;The web vault needs a secure context for the browser's Web Crypto API. That is the browser's rule, not Bitwarden's and not Vaultwarden's, and nobody in the chain can waive it. Serve the vault over plain HTTP from anything other than &lt;code&gt;localhost&lt;/code&gt; and the crypto calls fail — historically surfacing as &lt;code&gt;Cannot read property 'importKey'&lt;/code&gt;, which tells you nothing about the actual cause.&lt;/p&gt;

&lt;p&gt;The desktop client is a separate and newer restriction. Bitwarden's clients repo added &lt;code&gt;PM-25250 Prevent configuration and access of self-hosted URLs over http&lt;/code&gt;, which rejects HTTP self-hosted URLs outright, permitting them only in development mode. So "the app worked over HTTP last year" is a true memory, and no longer a working configuration.&lt;/p&gt;

&lt;p&gt;Either way: real certificate, real reverse proxy. The master password hash crosses that connection.&lt;/p&gt;

&lt;p&gt;So you need a reverse proxy with a real certificate. If you're starting from nothing, &lt;a href="https://sudosecurity.org/installing-nginx-on-debian-ubuntu-linux-distributions/" rel="noopener noreferrer"&gt;installing nginx on Debian and Ubuntu&lt;/a&gt; covers getting it on the box; what follows is only the Vaultwarden-specific part.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server {
    listen 443 ssl;
    http2 on;
    server_name vault.example.com;

    ssl_certificate     /etc/letsencrypt/live/vault.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/vault.example.com/privkey.pem;

    # Attachments and imports. The default 1m rejects a large vault import.
    client_max_body_size 128M;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host              $host;
        proxy_set_header X-Real-IP         $remote_addr;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Same upstream, same port. This block exists only to add the
    # upgrade headers WebSocket needs.
    location /notifications/hub {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host       $host;
        proxy_set_header X-Real-IP  $remote_addr;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Three things people get wrong here. &lt;code&gt;client_max_body_size&lt;/code&gt; at nginx's 1MB default will reject a vault import from LastPass or 1Password and produce an error message that says nothing useful. And &lt;code&gt;/notifications/anonymous-hub&lt;/code&gt; handles passwordless login approvals; if you only add upgrade headers to &lt;code&gt;/hub&lt;/code&gt;, login-with-device silently stops working while everything else looks healthy.&lt;/p&gt;

&lt;p&gt;The third is that &lt;code&gt;http2 on;&lt;/code&gt; needs nginx 1.25.1 or newer. On anything older it is not ignored, it is fatal:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ nginx -t
[emerg] unknown directive "http2" in /etc/nginx/conf.d/vault.conf:6
nginx: configuration file test failed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That is nginx 1.24.0, which is what Ubuntu 24.04 LTS and Debian 12 ship — so a large share of the people reading this. On those, use the older &lt;code&gt;listen 443 ssl http2;&lt;/code&gt; and drop the separate directive. I tested the block above both ways on 1.24.0: the legacy form passes &lt;code&gt;nginx -t&lt;/code&gt;, the modern one refuses to load. Check &lt;code&gt;nginx -v&lt;/code&gt; before you copy either.&lt;/p&gt;

&lt;h2&gt;
  
  
  Verify Before You Trust It
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;docker compose up -d&lt;/code&gt; and the container comes up. Don't stop there.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl -fsS http://127.0.0.1:8080/alive
"2026-09-11T14:22:07.481293Z"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;/alive&lt;/code&gt; is the endpoint the image's own bundled healthcheck hits, on &lt;code&gt;ROCKET_PORT&lt;/code&gt;, every 60 seconds. It returns a timestamp and nothing else.&lt;/p&gt;

&lt;p&gt;Now read the first twenty lines of the log, which is the step almost nobody bothers with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ docker logs vaultwarden 2&amp;gt;&amp;amp;1 | head -20
[WARNING] The following environment variables are being overridden by the config.json file.
[WARNING] Please use the admin panel to make changes to them:
[WARNING] domain, signups_allowed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That warning comes out of &lt;code&gt;src/config.rs&lt;/code&gt; before the logger is initialised, which is why it has no timestamp and scrolls past in the first half-second. It means &lt;code&gt;/data/config.json&lt;/code&gt; exists — because somebody once opened the admin panel and clicked Save — and every key in that file beats your environment.&lt;/p&gt;

&lt;p&gt;This is the single most expensive gotcha in Vaultwarden. You edit &lt;code&gt;docker-compose.yml&lt;/code&gt;, restart, and nothing changes. Not silently failing. Working exactly as designed, on values you can't see from the file you're editing. Either make the change in the admin panel, or delete the key from &lt;code&gt;config.json&lt;/code&gt; and restart.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Admin Token Preset Most Guides Get Backwards
&lt;/h2&gt;

&lt;p&gt;The admin panel at &lt;code&gt;/admin&lt;/code&gt; is a single-secret door. Don't put a plaintext token behind it; Vaultwarden will hash one for you. From &lt;code&gt;src/main.rs&lt;/code&gt; at 1.37.5:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;COMMAND:
    hash [--preset {bitwarden|owasp}]  Generate an Argon2id PHC ADMIN_TOKEN
    backup                             Create a backup of the SQLite database
                                       You can also send the USR1 signal to trigger a backup

PRESETS:                  m=         t=          p=
    bitwarden (default) 64MiB, 3 Iterations, 4 Threads
    owasp               19MiB, 2 Iterations, 1 Thread
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Read the presets. &lt;code&gt;bitwarden&lt;/code&gt; is the default and the stronger of the two: 65540 KiB, t=3, p=4, against owasp's 19456 KiB, t=2, p=1. Guides that tell you to run &lt;code&gt;vaultwarden hash --preset owasp&lt;/code&gt; are telling you to take 30% of the memory cost and a quarter of the parallelism, whatever they intended. The &lt;code&gt;owasp&lt;/code&gt; preset exists for hardware that can't spare 64MiB. Everywhere else, run it bare:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ docker run --rm -it vaultwarden/server:1.37.5 /vaultwarden hash
Generate an Argon2id PHC string using the 'bitwarden' preset:

Password:
Confirm Password:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then, in a compose file, escape every &lt;code&gt;$&lt;/code&gt; as &lt;code&gt;$$&lt;/code&gt; and wrap the whole thing in single quotes. This is called out explicitly in the upstream template and it is the most common reason a correctly generated token silently fails to authenticate.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ADMIN_SESSION_LIFETIME&lt;/code&gt; defaults to 20 minutes, which is fine. &lt;code&gt;DISABLE_ADMIN_TOKEN&lt;/code&gt; should stay &lt;code&gt;false&lt;/code&gt; unless something else is actually doing the authentication — a &lt;a href="https://sudosecurity.org/zero-trust-access-for-homelabbers/" rel="noopener noreferrer"&gt;zero-trust access layer&lt;/a&gt; in front of the route, not an assumption that nobody will guess the path.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lock the Door. The Whitelist Unlocks It.
&lt;/h2&gt;

&lt;p&gt;Standard advice is &lt;code&gt;SIGNUPS_ALLOWED=false&lt;/code&gt;. Then, because you want your own domain to be able to register, you reach for the whitelist. Here is what the upstream template says about that setting:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Controls if new users from a list of comma-separated domains can register
## even if SIGNUPS_ALLOWED is set to false
# SIGNUPS_DOMAINS_WHITELIST=example.com,example.net,example.org
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Read that second line twice. The whitelist is not a filter narrowing open registration. It is an override that punches straight through &lt;code&gt;SIGNUPS_ALLOWED=false&lt;/code&gt;. Set both and you haven't restricted anything. You have re-enabled registration for anyone holding an address at those domains.&lt;/p&gt;

&lt;p&gt;If signups are closed, close them. &lt;code&gt;INVITATIONS_ALLOWED=true&lt;/code&gt; plus invites from the admin panel requires possession of a link, not a plausible email suffix.&lt;/p&gt;

&lt;p&gt;And if you have SSO configured, check the other door. 1.37.3 added &lt;code&gt;SSO_SIGNUPS_ALLOWED&lt;/code&gt;, and it defaults to &lt;code&gt;true&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Allow SSO flow to create account. You probably want to disable it when using a public provider.
# SSO_SIGNUPS_ALLOWED=true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;SIGNUPS_ALLOWED=false&lt;/code&gt; does not close that path. The upstream comment tells you what to worry about: point Vaultwarden at a provider that will issue a token to anyone, and account creation is open again through a route you closed somewhere else.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two Settings Named Almost Nothing Like What They Do
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;REQUIRE_DEVICE_EMAIL&lt;/code&gt; is not email verification at signup. It is a new-device login notification, and it is off by default:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Require new device emails. When a user logs in an email is required to be sent.
## If sending the email fails the login attempt will fail!!
# REQUIRE_DEVICE_EMAIL=false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Those two exclamation marks are upstream, not mine. If your SMTP relay is down, nobody logs in. It couples vault availability to mail availability, permanently. Turn it on only once you are monitoring mail delivery.&lt;/p&gt;

&lt;p&gt;The setting you wanted for signup verification is &lt;code&gt;SIGNUPS_VERIFY&lt;/code&gt;, also &lt;code&gt;false&lt;/code&gt; by default, and in the compose file above.&lt;/p&gt;

&lt;p&gt;The one almost nobody enables is worth more than either:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# INCOMPLETE_2FA_TIME_LIMIT=3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;An incomplete 2FA login is one where the correct master password was accepted and the second factor was never completed. That is the exact signature of a compromised master password meeting a second factor that held. Vaultwarden emails the user after three minutes. It's on by default; don't set the limit to &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A note on the schedule, because the format misleads: &lt;code&gt;INCOMPLETE_2FA_SCHEDULE="30 * * * * *"&lt;/code&gt; is a six-field cron, so the leading &lt;code&gt;30&lt;/code&gt; is the second of each minute. The job runs once a minute, not every thirty seconds. The template says so plainly.&lt;/p&gt;

&lt;p&gt;Speaking of second factors — set one up. TOTP and WebAuthn both work with no server configuration at all, and WebAuthn means the &lt;a href="https://sudosecurity.org/passkeys-will-replace-passwords/" rel="noopener noreferrer"&gt;passkey&lt;/a&gt; in your phone or your hardware key. Email 2FA needs SMTP, and it is the weakest of the three; it also happens to be the subsystem in the CVE below.&lt;/p&gt;

&lt;p&gt;Then look at the "remember me" checkbox next to it, because that is where two of the last three releases landed. 1.37.3 shipped a security fix described as revoking 2FA remember tokens when credentials or 2FA settings change — meaning that before it, rotating your master password or replacing your authenticator left previously-remembered devices remembered. 1.37.5 then added a bound on how long that can last:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Number of days before a remembered 2FA login expires (min: 1, max: 90).
# TWO_FACTOR_REMEMBER_DAYS=30
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Thirty days by default, and &lt;code&gt;src/config.rs&lt;/code&gt; rejects anything outside 1 to 90 at startup rather than clamping it. If you would rather not have the checkbox at all, &lt;code&gt;DISABLE_2FA_REMEMBER=true&lt;/code&gt; ignores it — the template is explicit that the box stays visible either way, which is its own small usability trap.&lt;/p&gt;

&lt;h2&gt;
  
  
  Your Accounts Are on PBKDF2
&lt;/h2&gt;

&lt;p&gt;This one gets missed because it is not a server setting. New accounts are created server-side with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
pub const CLIENT_KDF_ITER_DEFAULT: i32 = 600_000;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That is &lt;code&gt;src/db/models/user.rs&lt;/code&gt; at 1.37.5. PBKDF2-SHA256 at 600,000 iterations: the Bitwarden-compatible default, and not weak. It is the memory-cheap option, and GPU attackers price memory-cheap KDFs very differently from memory-hard ones.&lt;/p&gt;

&lt;p&gt;Argon2id has been supported on the clients since Vaultwarden 1.28.0, and it is a per-account choice made in the client rather than a server flag. Web vault, then Settings, Security, Keys, change KDF to Argon2id. Every device gets logged out afterwards. Do it on a day when you can re-authenticate all of them.&lt;/p&gt;

&lt;p&gt;While you are in the source: &lt;code&gt;PASSWORD_ITERATIONS=600000&lt;/code&gt; in the template is the &lt;em&gt;server-side&lt;/em&gt; hash of the password hash. Different value, different place, and changing one doesn't change the other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Org Creation Is Open and Nothing Is Logged
&lt;/h2&gt;

&lt;p&gt;Two defaults that are reasonable for a hosted product and wrong for your box.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Controls which users can create new orgs.
## Blank or 'all' means all users can create orgs (this is the default):
# ORG_CREATION_USERS=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Every user on your instance can create organisations. Given where the 2026 advisories landed — see the table below, the answer is "the org permission model" — a family instance should set &lt;code&gt;ORG_CREATION_USERS=none&lt;/code&gt; and let you create them.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Controls whether event logging is enabled for organizations
## This setting applies to organizations.
## Disabled by default. Also check the EVENT_CLEANUP_SCHEDULE and EVENTS_DAYS_RETAIN settings.
# ORG_EVENTS_ENABLED=false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Org audit logging is off out of the box. If something happens inside an organisation, there is no record of it unless you turned this on beforehand. There's no retroactive audit log. Pair it with &lt;code&gt;EVENTS_DAYS_RETAIN&lt;/code&gt; — unset, the cleanup job never starts and the events table grows without limit.&lt;/p&gt;

&lt;p&gt;One housekeeping item if you run orgs and are coming from anything before 1.37.4: that release fixed an advisory covering the organisation API key (GHSA-qwx4-wcv4-mpcv), where Admins could view a key they should not have been able to. Upstream's own upgrade note says to consider rotating it after updating. Patching closes the hole; it does not un-disclose a key that was already readable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Your Rate Limits Are Rate Limiting a Header
&lt;/h2&gt;

&lt;p&gt;Vaultwarden derives the client address for login and admin rate limits from a header. Which header, and whose word it takes for it, are two different settings:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Client IP Header, used to identify the IP of the client, defaults to "X-Real-IP"
## Set to the string "none" (without quotes), to disable any headers and just use the remote IP
# IP_HEADER=X-Real-IP

## Which addresses the header above is accepted from, defaults to "local".
## Anyone able to reach Vaultwarden can set the header, and the client IP is used for the login and
## admin rate limits, so it is only trusted when the request comes from a proxy listed here.
## "local" accepts it from any non global address, which covers a reverse proxy running on the same
## host or container network. Use "all" to accept it from anywhere, or list the addresses of your
## proxy as IPs and CIDR ranges if it connects from a public address.
## For a list header like X-Forwarded-For, the client IP is the rightmost address that isn't one of
## these proxies, so with several proxies in a row (a CDN in front of nginx, for example) list all of them.
# IP_HEADER_TRUSTED_PROXIES=local
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;IP_HEADER_TRUSTED_PROXIES&lt;/code&gt; arrived in 1.37.0, in the pull request titled "Trusted proxy support, unauthenticated rate limit &amp;amp; other fixes." It cuts both ways.&lt;/p&gt;

&lt;p&gt;Those last two comment lines are new. They were added in 1.37.4, on 5 October 2026, and they document a change in behaviour rather than a new setting — which is the kind of thing that does not look like an upgrade note until it has already cost you something. If you use &lt;code&gt;IP_HEADER=X-Forwarded-For&lt;/code&gt;, Vaultwarden now takes the &lt;strong&gt;rightmost&lt;/strong&gt; address in the list that is not a trusted proxy. It used to take the leftmost.&lt;/p&gt;

&lt;p&gt;That is the correct direction, and it is correct for the reason the leftmost was wrong: &lt;code&gt;X-Forwarded-For&lt;/code&gt; is append-only, every proxy adds to the right, and the leftmost entry is whatever the original client sent — which an attacker controls completely. Taking the leftmost meant the limiter was metering a string from the request. Taking the rightmost-untrusted means it meters the last address a machine you trust actually saw.&lt;/p&gt;

&lt;p&gt;The consequence for anyone running more than one hop: every proxy in the chain has to be listed in &lt;code&gt;IP_HEADER_TRUSTED_PROXIES&lt;/code&gt;. Cloudflare in front of nginx is two hops. Miss the inner one and Vaultwarden stops at it, deciding your own nginx is the client, and every request on the instance shares one rate-limit bucket and one address in the logs. If you are on &lt;code&gt;X-Real-IP&lt;/code&gt; with a single local proxy — the configuration in the nginx block above — none of this touches you.&lt;/p&gt;

&lt;p&gt;Set it to &lt;code&gt;all&lt;/code&gt; — which forum answers suggest whenever someone's fail2ban is banning the proxy's own address — and every attacker gets a fresh rate-limit bucket per forged &lt;code&gt;X-Real-IP&lt;/code&gt;. The limiter still runs. It's metering an attacker-controlled string. If the proxy is on the same host or container network, &lt;code&gt;local&lt;/code&gt; is correct; leave it alone. If it arrives from a public address, list those ranges. Never &lt;code&gt;all&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then the numbers. These are the upstream defaults:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# ADMIN_RATELIMIT_SECONDS=300
# ADMIN_RATELIMIT_MAX_BURST=3
# LOGIN_RATELIMIT_SECONDS=60
# LOGIN_RATELIMIT_MAX_BURST=10
# UNAUTHENTICATED_RATELIMIT_SECONDS=60
# UNAUTHENTICATED_RATELIMIT_MAX_BURST=50
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A very widely copied config block sets &lt;code&gt;ADMIN_RATELIMIT_SECONDS: "60"&lt;/code&gt; under a comment reading "Admin page rate limiting." The default is 300. Writing 60 there doesn't harden the admin panel. It makes admin login attempts five times cheaper than stock Vaultwarden allows. The login values in that same block are already the defaults, so those two lines do nothing at all. This is why the compose file above omits the section entirely.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;UNAUTHENTICATED_RATELIMIT_*&lt;/code&gt; is also new in 1.37.0: a shared budget covering password hints, account recovery mail, and Send access, which were not metered as a group before.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Oracle at /api/two-factor/send-email-login
&lt;/h2&gt;

&lt;p&gt;The rate limiter has been bypassed outright, and recently.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CVE-2026-43914&lt;/code&gt; (GHSA-c5rv-q295-7w4g, CVSS 3.1 base 7.3, &lt;code&gt;AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L&lt;/code&gt;, CWE-307) covers Vaultwarden before 1.35.4. The &lt;code&gt;check_limit_login&lt;/code&gt; guard was applied to &lt;code&gt;_sso_login&lt;/code&gt;, &lt;code&gt;_password_login&lt;/code&gt; and &lt;code&gt;_api_key_login&lt;/code&gt;. It was not applied to &lt;code&gt;send_email_login&lt;/code&gt;, the handler behind &lt;code&gt;/api/two-factor/send-email-login&lt;/code&gt;. That endpoint answers differently depending on whether the submitted master password is correct, so it functions as an unmetered password oracle.&lt;/p&gt;

&lt;p&gt;The part worth sitting with: per the CVE record, it worked against users who had no email 2FA configured, provided email 2FA was enabled on the server. The exposed population wasn't "people using email 2FA." It was everyone on an instance where email 2FA existed as an option.&lt;/p&gt;

&lt;p&gt;The disclosure timeline matters more than the bug. The fix shipped in 1.35.4 on 23 February 2026. The advisory published 25 April. The CVE published 11 May. Seventy-seven days in which the patched release was public and the reason for it was not. Anyone waiting on a CVE feed spent eleven weeks on a known-broken auth path.&lt;/p&gt;

&lt;p&gt;That is the operating model, not an anomaly:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Release&lt;/th&gt;
&lt;th&gt;Date&lt;/th&gt;
&lt;th&gt;Security content&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1.35.3&lt;/td&gt;
&lt;td&gt;10 Feb&lt;/td&gt;
&lt;td&gt;Cross-collection item access&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.35.4&lt;/td&gt;
&lt;td&gt;23 Feb&lt;/td&gt;
&lt;td&gt;Cipher access by UUID; two Manager-role collection flaws&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.35.5&lt;/td&gt;
&lt;td&gt;12 Apr&lt;/td&gt;
&lt;td&gt;Unconfirmed owner can purge org vault; cross-org group binding; refresh tokens surviving stamp rotation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.36.0&lt;/td&gt;
&lt;td&gt;3 May&lt;/td&gt;
&lt;td&gt;SSO login CSRF; user/org enumeration; SSO existing-user binding; icon SSRF&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.37.0&lt;/td&gt;
&lt;td&gt;24 Jul&lt;/td&gt;
&lt;td&gt;Eight entries, ten GHSA IDs: icon SSRF, cross-org cipher access, policy bypass on directory import, Send access-count bypass, unauthenticated WebSocket flood, cross-org secret sharing, org import authz, Manager-role enumeration&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.37.3&lt;/td&gt;
&lt;td&gt;13 Sep&lt;/td&gt;
&lt;td&gt;Two, unnumbered: 2FA remember tokens not revoked on credential or 2FA change; prelogin and auth-request endpoints not rate limited&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.37.4&lt;/td&gt;
&lt;td&gt;5 Oct&lt;/td&gt;
&lt;td&gt;Seven advisories, one High — org member revocation (GHSA-69q9-v8p6-xvx3, 8.1), two-factor authentication (GHSA-7jg8-8m5x-6j9r, 6.8), org invitations (GHSA-v576-3wvq-xh3c, 6.8), attachments (GHSA-q5x6-grh5-fqgc, 6.5), org event logs (GHSA-64mc-4p6f-r7x9, 4.3), cipher sharing (GHSA-7ccc-c43j-4p36, 4.3), org API key (GHSA-qwx4-wcv4-mpcv, 3.8)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.37.5&lt;/td&gt;
&lt;td&gt;1 Nov&lt;/td&gt;
&lt;td&gt;Two: website icons (GHSA-x9cq-f669-vrr4, 5.3) and emergency access (GHSA-9pjj-f9g5-3x4c, 4.3)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Three patterns fall out, and the third one is the reason this article got rewritten. First, the org and collection permission model is where the bugs live. Cross-org, cross-collection, Manager-role scope: the boundary keeps turning out wider than intended. Run a single-user instance and you dodged most of 2026. Run organisations and your upgrade window is days, not quarters.&lt;/p&gt;

&lt;p&gt;Second, releases carrying security fixes say so before CVEs exist — 1.37.0's notes state the advisories are private pending CVE assignment, and 1.37.4's and 1.37.5's say the same thing word for word. Watch the releases page, not a vulnerability feed. Subscribe to the repo's releases and you get the notification the day it matters.&lt;/p&gt;

&lt;p&gt;How long that gap runs is now measurable rather than estimated. 1.37.0 shipped on 24 July with eight advisories named and withheld. Those advisories published on 3 October — all ten of them, same day — which is seventy-one days of a public patch with a private reason. The 1.37.4 and 1.37.5 advisories, seven and two respectively, are still private as of this writing. If your upgrade trigger is a CVE feed, that is the length of your exposure window, and it is not a one-off.&lt;/p&gt;

&lt;p&gt;Third: the rate of this has gone up, not down. Between the first version of this article and this one — eight weeks — Vaultwarden shipped three releases carrying eleven security advisories between them, including the first High-severity entry of the year at 8.1. Nothing in the hardening advice below changed. The version you should be running did, three times.&lt;/p&gt;

&lt;p&gt;The icon SSRF entries carry their own lesson. Vaultwarden already ships the defence:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Enabling this will cause the internal HTTP client to refuse to connect to any non-global IP address.
# HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS=true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Default on. So the 2026 bypasses were not missing controls; one is catalogued upstream as a decimal/hex/octal IP encoding bypass. The control was correct. The parser in front of it wasn't, which is &lt;a href="https://sudosecurity.org/what-is-ssrf/" rel="noopener noreferrer"&gt;SSRF&lt;/a&gt; behaving exactly as it always does — the check and the thing being checked disagreeing about what a string means. If your instance has no business fetching favicons, &lt;code&gt;ICON_SERVICE&lt;/code&gt; accepts &lt;code&gt;bitwarden&lt;/code&gt;, &lt;code&gt;duckduckgo&lt;/code&gt; or &lt;code&gt;google&lt;/code&gt; to hand the fetch off entirely, or &lt;code&gt;DISABLE_ICON_DOWNLOAD=true&lt;/code&gt; with &lt;code&gt;ICON_CACHE_TTL=0&lt;/code&gt; stops it dead.&lt;/p&gt;

&lt;h2&gt;
  
  
  If You Are on MySQL or MariaDB, Read This Before You Upgrade
&lt;/h2&gt;

&lt;p&gt;Everything above assumes SQLite, which is the default and the right choice for a household. If you moved to MariaDB or MySQL at some point, there is an upgrade that stops your server from starting, and it's much better known about in advance than after.&lt;/p&gt;

&lt;p&gt;Vaultwarden 1.36.0 added item archiving, and with it a migration called &lt;code&gt;2026-03-09-005927_add_archives&lt;/code&gt;. On some MariaDB installs it fails and takes the process with it:&lt;/p&gt;

&lt;p&gt;Migrations run at startup, and the runner does not handle failure gracefully. From &lt;code&gt;src/db/mod.rs&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        diesel::sql_query("SET FOREIGN_KEY_CHECKS = 0")
            .execute(&amp;amp;mut connection)
            .expect("Failed to disable Foreign Key Checks during migrations");

        connection.run_pending_migrations(MIGRATIONS).expect("Error running migrations");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That &lt;code&gt;.expect()&lt;/code&gt; is a panic. This is not a degraded feature or a missing archive button — the process dies on boot and your vault is unreachable until you fix the database.&lt;/p&gt;

&lt;p&gt;Read the line above it as well, because it matters for what follows. Vaultwarden explicitly turns foreign key checks &lt;strong&gt;off&lt;/strong&gt; before migrating. The reasonable conclusion is that a foreign key problem therefore cannot stop a migration. That conclusion is wrong, and I only know it is wrong because I tested it both ways.&lt;/p&gt;

&lt;p&gt;Here is the migration, verbatim from &lt;code&gt;migrations/mysql/2026-03-09-005927_add_archives/up.sql&lt;/code&gt; at 1.37.5 — byte-identical to the version that shipped in 1.36.0:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DROP TABLE IF EXISTS archives;

CREATE TABLE archives (
    user_uuid   CHAR(36) NOT NULL,
    cipher_uuid CHAR(36) NOT NULL,
    archived_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_uuid, cipher_uuid),
    FOREIGN KEY (user_uuid) REFERENCES users (uuid) ON DELETE CASCADE,
    FOREIGN KEY (cipher_uuid) REFERENCES ciphers (uuid) ON DELETE CASCADE
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Nothing wrong with it in isolation. The problem is what it doesn't say. Grep every MySQL migration in the repo and not one pins a character set or collation, so every table inherits whatever the database default was on the day it was created. InnoDB requires a foreign key's column to match the referenced column's type &lt;em&gt;and&lt;/em&gt; charset &lt;em&gt;and&lt;/em&gt; collation exactly. If &lt;code&gt;users&lt;/code&gt; and &lt;code&gt;ciphers&lt;/code&gt; were created years ago under one default and &lt;code&gt;archives&lt;/code&gt; is created today under another, the constraint is rejected.&lt;/p&gt;

&lt;p&gt;I reproduced it. MariaDB 10.11.14: create &lt;code&gt;users&lt;/code&gt; and &lt;code&gt;ciphers&lt;/code&gt; in a database defaulting to &lt;code&gt;utf8mb3_general_ci&lt;/code&gt;, move the database default to &lt;code&gt;utf8mb4_general_ci&lt;/code&gt; the way a server upgrade or a tidy-minded admin would, then run the real migration file — prefixed with the same statement Vaultwarden's own runner issues.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ { echo "SET FOREIGN_KEY_CHECKS = 0;"; cat 2026-03-09-005927_add_archives/up.sql; } | mysql vw
ERROR 1005 (HY000) at line 4: Can't create table `vw`.`archives` (errno: 150 "Foreign key constraint is incorrectly formed")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Exit code 1, &lt;code&gt;archives&lt;/code&gt; not created, zero foreign keys on it. &lt;code&gt;FOREIGN_KEY_CHECKS = 0&lt;/code&gt; suppresses &lt;em&gt;referential&lt;/em&gt; checking — it lets you create a constraint pointing at a table that does not exist yet, which is why migration tooling sets it. It doesn't suppress &lt;em&gt;structural&lt;/em&gt; validation. A charset or collation mismatch makes the constraint malformed rather than merely unsatisfied, and InnoDB rejects a malformed constraint whether checking is on or off. I ran it both ways and got the identical error on the identical line.&lt;/p&gt;

&lt;p&gt;So check before you pull the new image:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT TABLE_NAME, TABLE_COLLATION
  FROM information_schema.TABLES
 WHERE TABLE_SCHEMA = 'vaultwarden';

SELECT @@character_set_database, @@collation_database;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If the existing tables and the database default disagree, you are holding the failure.&lt;/p&gt;

&lt;p&gt;The obvious fix doesn't work, which is the part worth knowing. Converting the old tables to match the new default is the first thing anybody tries, and InnoDB refuses:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mysql vw -e "ALTER TABLE users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
ERROR 1833 (HY000): Cannot change column 'uuid': used in a foreign key constraint 'vw/ciphers_ibfk_1' of table 'vw/ciphers'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can't retype a column another table's foreign key points at, and Vaultwarden's schema is full of them. Dropping every constraint, converting, and rebuilding them is a long evening with your vault offline.&lt;/p&gt;

&lt;p&gt;Move the database default instead. Point it back at whatever the existing tables already use, let the migration inherit that, and nothing has to be rewritten:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mysql -e "ALTER DATABASE vaultwarden DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci;"
$ mysql vaultwarden &amp;lt; 2026-03-09-005927_add_archives/up.sql
$ mysql vaultwarden -e "SELECT TABLE_NAME, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA='vaultwarden';"
TABLE_NAME      TABLE_COLLATION
archives        utf8mb3_general_ci
ciphers         utf8mb3_general_ci
users           utf8mb3_general_ci
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Exit code 0, both foreign keys land, Vaultwarden starts. Substitute your own collation — the point is that it matches the tables you already have, not that it is that particular value. In practice you set the database default and then start the new image, letting Vaultwarden run the migration itself.&lt;/p&gt;

&lt;p&gt;Two caveats, stated plainly. I reproduced this on a synthetic two-table schema, not on a real years-old Vaultwarden database, so treat the mechanism as confirmed and the specifics of your own install as unknown until you run those two queries. And take a &lt;code&gt;mysqldump&lt;/code&gt; before any of it. This is the upgrade where you want a rollback.&lt;/p&gt;

&lt;p&gt;One more MySQL item, unrelated but in the same place: 1.37.4 changed the Alpine images so they may fail to reach a MariaDB or MySQL server that has no native TLS. The fix upstream names is &lt;code&gt;MARIADB_TLS_DISABLE_PEER_VERIFICATION=1&lt;/code&gt;, and it is an environment variable only — it does not appear in &lt;code&gt;.env.template&lt;/code&gt;, so grepping the template for it tells you nothing. If your Alpine container stopped connecting to its database at 1.37.4, that is why.&lt;/p&gt;

&lt;h2&gt;
  
  
  Backups: The Command in Your Cron Job Does Not Exist
&lt;/h2&gt;

&lt;p&gt;Here is the runtime stage of &lt;code&gt;docker/Dockerfile.debian&lt;/code&gt; at 1.37.5:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM --platform=$TARGETPLATFORM docker.io/library/debian:trixie-slim

# Create data folder and Install needed libraries
RUN mkdir /data &amp;amp;&amp;amp; \
    apt-get update &amp;amp;&amp;amp; apt-get install -y \
        --no-install-recommends \
        ca-certificates \
        curl \
        libmariadb3 \
        libpq5 \
        openssl &amp;amp;&amp;amp; \
    apt-get clean &amp;amp;&amp;amp; \
    rm -rf /var/lib/apt/lists/*
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;ca-certificates&lt;/code&gt;, &lt;code&gt;curl&lt;/code&gt;, &lt;code&gt;libmariadb3&lt;/code&gt;, &lt;code&gt;libpq5&lt;/code&gt;, &lt;code&gt;openssl&lt;/code&gt;. There's no &lt;code&gt;sqlite3&lt;/code&gt; binary in that image. Every backup script built on &lt;code&gt;docker exec vaultwarden sqlite3 /data/db.sqlite3 ".backup ..."&lt;/code&gt; fails on the official container, and it fails before the tarball is assembled — so what lands in your offsite bucket is a compressed folder of attachments with no database in it. Every night. Quietly. For as long as you let it.&lt;/p&gt;

&lt;p&gt;Vaultwarden has had a first-party backup path for a while, and since April 2026 it uses &lt;code&gt;VACUUM INTO&lt;/code&gt; rather than the legacy backup API. From &lt;code&gt;src/db/mod.rs&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        diesel::sql_query("VACUUM INTO ?")
            .bind::&amp;lt;diesel::sql_types::Text, _&amp;gt;(&amp;amp;backup_file)
            .execute(&amp;amp;mut conn)
            .map(|_| ())
            .map_res("VACUUM INTO failed")?;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It opens the database read-only, writes &lt;code&gt;db_YYYYMMDD_HHMMSS.sqlite3&lt;/code&gt; beside the original, and being a single SQLite statement it produces a consistent snapshot with the WAL already folded in. No &lt;code&gt;-wal&lt;/code&gt; and &lt;code&gt;-shm&lt;/code&gt; juggling. Two ways to trigger it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Signal the running process. No downtime, result goes to the log.
docker kill -s USR1 vaultwarden

# Or run the subcommand as a separate read-only process.
docker exec vaultwarden /vaultwarden backup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then take the snapshot, &lt;code&gt;attachments/&lt;/code&gt;, &lt;code&gt;sends/&lt;/code&gt;, and &lt;code&gt;rsa_key&lt;/code&gt;. That last one isn't optional. It is a 2048-bit RSA key generated on first start and loaded into &lt;code&gt;PRIVATE_RSA_KEY&lt;/code&gt; in &lt;code&gt;src/auth.rs&lt;/code&gt;; every JWT the server issues is signed with it. Restore without it and Vaultwarden generates a fresh one, invalidating every session and token in existence. Skip &lt;code&gt;icon_cache/&lt;/code&gt;. It rebuilds.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/bin/bash
# /opt/scripts/vaultwarden-backup.sh
set -euo pipefail

STAMP=$(date +%Y%m%d-%H%M)
DATA=/opt/vaultwarden/data
DEST=/opt/backups/vaultwarden

docker kill -s USR1 vaultwarden
sleep 5

# VACUUM INTO writes db_YYYYMMDD_HHMMSS.sqlite3 alongside the live database.
SNAP=$(find "${DATA}" -maxdepth 1 -name 'db_*.sqlite3' -printf '%T@ %p\n' \
       | sort -rn | head -1 | cut -d' ' -f2-)
[ -n "${SNAP}" ] || { echo "no snapshot produced -- check container logs"; exit 1; }

mkdir -p "${DEST}/${STAMP}"
mv "${SNAP}" "${DEST}/${STAMP}/db.sqlite3"
cp -r "${DATA}/attachments" "${DATA}/sends" "${DATA}/rsa_key" "${DEST}/${STAMP}/" 2&amp;gt;/dev/null || true

tar -czf "${DEST}/${STAMP}.tar.gz" -C "${DEST}" "${STAMP}"
rm -rf "${DEST:?}/${STAMP}"

# Encrypt before it leaves the box. age-keygen -o /opt/backup-key.txt, once.
age -r "$(grep '^# public key:' /opt/backup-key.txt | awk '{print $NF}')" \
    -o "${DEST}/${STAMP}.tar.gz.age" "${DEST}/${STAMP}.tar.gz"
rm "${DEST}/${STAMP}.tar.gz"

find "${DEST}" -name '*.age' -mtime +30 -delete
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;exit 1&lt;/code&gt; on a missing snapshot is the part that matters. A backup script that can't fail loudly will report success for a year.&lt;/p&gt;

&lt;p&gt;I have not timed that five-second sleep against a large database. It's a guess at how long &lt;code&gt;VACUUM INTO&lt;/code&gt; takes, and on a multi-gigabyte vault it'll be wrong. Run the script by hand, watch the log line, and set it from what you observe rather than from what I wrote.&lt;/p&gt;

&lt;p&gt;On PostgreSQL none of this applies. The &lt;code&gt;backup&lt;/code&gt; subcommand returns &lt;code&gt;The database type is not SQLite. Backups only works for SQLite databases&lt;/code&gt;, and the USR1 handler is never registered at all. Use &lt;code&gt;pg_dump&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And the part everyone skips: restore it. Spin up a second container against a copy of the backup, log in, read one password. A backup you have never restored is a hypothesis.&lt;/p&gt;

&lt;h2&gt;
  
  
  Drop Root
&lt;/h2&gt;

&lt;p&gt;The container runs as root. There's no &lt;code&gt;USER&lt;/code&gt; directive in the Dockerfile, and &lt;code&gt;ROCKET_PORT=80&lt;/code&gt;, so dropping privileges means moving the port as well:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    user: "1000:1000"
    environment:
      ROCKET_PORT: "8080"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Chown the data directory to match and repoint the proxy. The bundled healthcheck reads &lt;code&gt;ROCKET_PORT&lt;/code&gt; from the environment, so it follows along without changes.&lt;/p&gt;

&lt;h2&gt;
  
  
  When It Breaks
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Config changes have no effect.&lt;/strong&gt; &lt;code&gt;config.json&lt;/code&gt; is winning. Check the startup warning above, then either change it in the admin panel or delete the key from &lt;code&gt;/data/config.json&lt;/code&gt; and restart. The environment variable takes over once the key is gone.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Empty vault after changing the database.&lt;/strong&gt; Before 1.37.0, a &lt;code&gt;DATABASE_URL&lt;/code&gt; matching no known scheme fell through to SQLite and created a fresh, empty database — a typo in a Postgres URL produced a working, empty server. 1.37.0 changed that; the source comment is explicit that it "prevents misconfigured URLs (typos, quoted strings) from silently creating a new empty SQLite database." If this already happened on an older version, your real data is still where it was. Fix the URL. Do not let anything write to the new file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Clients connect but never sync in real time.&lt;/strong&gt; The &lt;code&gt;/notifications/hub&lt;/code&gt; proxy block, or its missing upgrade headers. Vaultwarden logs &lt;code&gt;WebSocket are disabled, realtime sync functionality will not work!&lt;/code&gt; at startup if &lt;code&gt;ENABLE_WEBSOCKET&lt;/code&gt; is off, which is the other half of the diagnosis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Login-with-device does nothing.&lt;/strong&gt; &lt;code&gt;/notifications/anonymous-hub&lt;/code&gt; is not proxied with upgrade headers. Worth knowing: the source caps it at &lt;code&gt;MAX_ANONYMOUS_CONNECTIONS_PER_IP: u32 = 25&lt;/code&gt;, added as the fix for the unauthenticated WebSocket flooding advisory in 1.37.0. Behind heavy NAT you can legitimately brush that ceiling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vault import fails on a big file.&lt;/strong&gt; &lt;code&gt;client_max_body_size&lt;/code&gt;. nginx defaults to 1MB.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;fail2ban bans nothing.&lt;/strong&gt; Three causes, and the third is one I got wrong in a draft of this piece. First, the line you are matching, at the default &lt;code&gt;LOG_LEVEL=info&lt;/code&gt; with &lt;code&gt;EXTENDED_LOGGING=true&lt;/code&gt; and the &lt;code&gt;[{timestamp}][{target}][{level}] {message}&lt;/code&gt; layout from &lt;code&gt;src/main.rs&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[2026-09-05 03:42:15.214][vaultwarden::api::identity][ERROR] Username or password is incorrect. Try again. IP: 203.0.113.42. Username: user@example.com.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Second, an INI section cannot have two &lt;code&gt;failregex =&lt;/code&gt; keys; the later silently replaces the earlier, so multiple patterns must be continuation lines.&lt;/p&gt;

&lt;p&gt;Third, the three lines you want are written at three different call sites and do not share punctuation:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/api/identity.rs:382
err!("Username or password is incorrect. Try again", format!("IP: {}. Username: {log_username}.", ip.ip))
// src/api/admin.rs:224
error!("Invalid admin token. IP: {}", ip.ip);
// src/api/admin.rs:905
error!("Invalid or expired admin JWT. IP: {}.", ip.ip);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The admin token line has no period after the address. The other two do. A pattern ending &lt;code&gt;IP: &amp;lt;ADDR&amp;gt;\.&lt;/code&gt; matches two of the three and silently drops the one guarding your admin panel.&lt;/p&gt;

&lt;p&gt;That &lt;code&gt;log_username&lt;/code&gt; is new in 1.37.5, and it is worth a moment. The line used to interpolate the submitted username raw. It is now &lt;code&gt;username.escape_debug()&lt;/code&gt;, from the commit titled "Escape request values in log messages" — which closes log injection, because the username field is attacker-supplied and a newline in it used to let somebody write their own lines into your log file. Anything parsing that log on trust was parsing attacker input.&lt;/p&gt;

&lt;p&gt;It does not break the patterns below, and that is worth checking rather than assuming:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user@example.com    -&amp;gt; IP: 203.0.113.42. Username: user@example.com.
ad"min@x.com        -&amp;gt; IP: 203.0.113.42. Username: ad\"min@x.com.
a[newline]b@x.com   -&amp;gt; IP: 203.0.113.42. Username: a\nb@x.com.
josé@example.com    -&amp;gt; IP: 203.0.113.42. Username: josé@example.com.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;escape_debug&lt;/code&gt; leaves ordinary addresses untouched, so the rendered line is byte-identical for every real user. The patterns here stop at the address and never look at the username anyway. But if you wrote a rule that matches on usernames — some people ban on repeated attempts against one account — that rule now sees escaped values, and a hostile username that used to smuggle a newline no longer does.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /etc/fail2ban/filter.d/vaultwarden.conf
[Definition]
failregex = ^\[[^\]]+\]\[[^\]]+\]\[ERROR\] Username or password is incorrect\. Try again\. IP: &amp;lt;ADDR&amp;gt;\.
            ^\[[^\]]+\]\[[^\]]+\]\[ERROR\] Invalid admin token\. IP: &amp;lt;ADDR&amp;gt;
            ^\[[^\]]+\]\[[^\]]+\]\[ERROR\] Invalid or expired admin JWT\. IP: &amp;lt;ADDR&amp;gt;\.
datepattern = ^\[%%Y-%%m-%%d %%H:%%M:%%S
ignoreregex =
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Do not take my word for it. &lt;code&gt;fail2ban-regex&lt;/code&gt; reports matches per pattern, and a pattern showing zero against a log full of failed logins is the whole bug, visible in one command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ fail2ban-regex /opt/vaultwarden/data/vaultwarden.log \
                 /etc/fail2ban/filter.d/vaultwarden.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Check &lt;code&gt;IP_HEADER_TRUSTED_PROXIES&lt;/code&gt; at the same time. If Vaultwarden is logging your proxy's address instead of the client's, fail2ban will faithfully ban your proxy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logs stop after logrotate.&lt;/strong&gt; Vaultwarden reopens &lt;code&gt;LOG_FILE&lt;/code&gt; on SIGHUP — &lt;code&gt;fern::log_reopen1(path, [SIGHUP])&lt;/code&gt; in &lt;code&gt;src/main.rs&lt;/code&gt;. Without a &lt;code&gt;postrotate&lt;/code&gt; that signals it, the process keeps writing to the rotated inode and the live log stays empty.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;postrotate
    docker kill -s HUP vaultwarden
endscript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Nobody can log in and mail is down.&lt;/strong&gt; &lt;code&gt;REQUIRE_DEVICE_EMAIL=true&lt;/code&gt;. That is the coupling described earlier, arriving.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mobile or the browser extension stopped working after a client update.&lt;/strong&gt; Compare the server version against the client version before debugging anything else. 1.37.0 is required for clients at 2026.7.0+, 1.37.2 for 2026.8.0+, and 1.37.5 before web vault 2026.7.1+ can toggle two-step login methods or 2026.9.0+ can take over an account via emergency access.&lt;/p&gt;

&lt;p&gt;The 2026.8.0 extension release is the example with a second half to it. Users across Chrome, Firefox, Edge and Vivaldi reported the extension failing to log in or showing an empty vault, with the server logging &lt;code&gt;2FA token not provided&lt;/code&gt;. Upgrading the server was necessary but on its own was not sufficient for everyone: the extension held cached state that survived the upgrade, and people got working again only after removing and reinstalling it. If the server is current and one client still misbehaves while others are fine, suspect that client's cache before you suspect your config.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Invites stopped working on 1.37.0.&lt;/strong&gt; A real regression, fixed in 1.37.1 on 29 July 2026. If you applied a local workaround at the time, upstream's notes ask you to revert it rather than carry it forward. 1.37.1 also fixed an OpenSSL build problem in the Alpine image.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The server refuses to start after upgrading to 1.37.4 or later, complaining about feature flags.&lt;/strong&gt; 1.37.4 removed several client feature flags. If &lt;code&gt;EXPERIMENTAL_CLIENT_FEATURE_FLAGS&lt;/code&gt; still names one, &lt;code&gt;src/config.rs&lt;/code&gt; builds this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let feature_flags_error = format!(
    "Unrecognized experimental client feature flags: {invalid_flags:?}.\n\
             Please ensure all feature flags are spelled correctly and that they are supported in this version.\n\
             Supported flags: {SUPPORTED_FEATURE_FLAGS:?}\n"
);
if on_update {
    err!(feature_flags_error);
}
println!("[WARNING] {feature_flags_error}");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Two different outcomes from one condition, which is why the symptom is confusing. At startup it is a &lt;code&gt;[WARNING]&lt;/code&gt; — printed before the logger exists, like the &lt;code&gt;config.json&lt;/code&gt; notice, so it scrolls past. Through the admin panel (&lt;code&gt;on_update&lt;/code&gt;) it is a hard error and your save fails. The message lists the flags it does support, so the fix is in the output. &lt;code&gt;DUO_USE_IFRAME&lt;/code&gt; was removed in the same release and is simply ignored if set.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A config value that used to be tolerated now stops startup.&lt;/strong&gt; 1.37.5 tightened validation: invalid values are rejected at boot rather than silently coerced, and several numeric options gained bounds. &lt;code&gt;TWO_FACTOR_REMEMBER_DAYS&lt;/code&gt; outside 1 to 90 and &lt;code&gt;INVITATION_EXPIRATION_HOURS&lt;/code&gt; below 1 both fail with a named error rather than clamping. If 1.37.5 will not start on a config that worked on 1.37.4, read the first error line rather than reaching for the previous tag.&lt;/p&gt;

&lt;p&gt;One thing worth wiring up while you are here: &lt;code&gt;/alive&lt;/code&gt; is a clean scrape target, and a password server going quiet is exactly the failure you want a page for rather than a discovery. If you already run &lt;a href="https://sudosecurity.org/prometheus-grafana-self-hosted-monitoring-complete-guide-2026/" rel="noopener noreferrer"&gt;Prometheus and Grafana&lt;/a&gt;, a blackbox probe against that endpoint is about four lines of config.&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Doesn't Cover
&lt;/h2&gt;

&lt;p&gt;SSO. Vaultwarden's OIDC support absorbed a large share of 2026's advisories — CSRF in the authorisation flow, existing-user binding, discovery-endpoint enumeration — and it deserves its own Saturday rather than three paragraphs here. Nothing above addresses it.&lt;/p&gt;

&lt;p&gt;Also out of scope: the S3 storage backend added in 1.37.0, PostgreSQL tuning, migrating between database backends, Duo, LDAP sync, and network placement. The MySQL section above is an upgrade warning, not a guide to running on it. Whether this should be on the public internet at all is a real argument with a defensible answer on both sides, and it is a proxy and access-layer question rather than a Vaultwarden one.&lt;/p&gt;

&lt;p&gt;The 1.37.4 and 1.37.5 advisories are summarised from the release notes and nothing else, because the advisories themselves are still private. Seven of them have a title and a score and no detail. I have not verified the mechanism behind any of the nine, and nobody outside the project can yet.&lt;/p&gt;

&lt;p&gt;I have not benchmarked the Argon2id migration against PBKDF2 on client hardware. The unlock-time cost is real and varies by device. Measure it on your oldest phone before you migrate a family onto it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Actual Point
&lt;/h2&gt;

&lt;p&gt;Vaultwarden is good software. Small, fast, seriously maintained, and the advisory cadence above is evidence of that rather than against it — those bugs were found, fixed, and disclosed with affected versions named and scores attached. Compare that with a vendor whose status page says no critical vulnerabilities found.&lt;/p&gt;

&lt;p&gt;It also tells you what it is not. The project's own wiki states it targets individuals, families and smaller organisations, and that features aimed mainly at large organisations — single sign-on, directory syncing — are not a development priority. Worth reading before you deploy it as a company password manager and then file issues about SSO.&lt;/p&gt;

&lt;p&gt;But the defaults are compatibility defaults, not hardening defaults. They exist so a Bitwarden client connects on the first try, on a Pi, behind whatever somebody has already built. Every setting in this piece has a reason to sit where it sits. None of those reasons is your threat model.&lt;/p&gt;

&lt;p&gt;So read the template. Not this guide, not the one you found on Reddit. The 700-line &lt;code&gt;.env.template&lt;/code&gt; that ships in the repo, at the tag you are actually running. It takes twenty minutes and it's the only document that can't be out of date.&lt;/p&gt;

</description>
      <category>selfhosted</category>
      <category>security</category>
      <category>docker</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build Your Own Stack-Based Bytecode Virtual Machine in C</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Tue, 17 Nov 2026 14:00:00 +0000</pubDate>
      <link>https://dev.to/sudosecurity/build-your-own-stack-based-bytecode-virtual-machine-in-c-73f</link>
      <guid>https://dev.to/sudosecurity/build-your-own-stack-based-bytecode-virtual-machine-in-c-73f</guid>
      <description>&lt;p&gt;You've heard the word "virtual machine" thrown around a thousand times. The Java Virtual Machine. The &lt;code&gt;CPython&lt;/code&gt; VM that powers &lt;code&gt;Python&lt;/code&gt;. The &lt;code&gt;Lua&lt;/code&gt; VM. The &lt;code&gt;WebAssembly&lt;/code&gt; runtime. They're everywhere. But do you actually know how they work?&lt;/p&gt;

&lt;p&gt;I mean really work — not the hand-wavy "it interprets bytecode" explanation, but the actual mechanics. The stack. The instruction pointer. The dispatch loop. The thing doing the work.&lt;/p&gt;

&lt;p&gt;I didn't. And then I decided to build one.&lt;/p&gt;

&lt;p&gt;This article is about implementing a stack-based bytecode virtual machine from scratch in C. We're going to define a real instruction set, implement a constant pool, write an execution loop, and run actual bytecode through it. By the end, you'll have a working VM that can execute two instructions — and, more importantly, you'll understand the foundation that makes every other instruction possible.&lt;/p&gt;

&lt;p&gt;Fair warning: this is Part 1. We've got 17 instructions total to implement. We're covering the foundation today, and the rest in follow-up articles. But the foundation is the hard part. Once you understand the loop, everything else is just more cases in a switch statement.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Even Is a Stack-Based Bytecode VM?
&lt;/h2&gt;

&lt;p&gt;Two concepts you need to lock in before writing a single line of code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First: the stack.&lt;/strong&gt; A stack is a list of slots that can hold values — numbers in our case. You can add values to it (push), remove values from it (pop), and access the top of it. That's it. It's dead simple, and it's one of the most fundamental data structures in computing. You've already seen one — the &lt;a href="https://sudosecurity.org/js-event-loop-deep-dive/" rel="noopener noreferrer"&gt;JavaScript call stack is a stack. The Java heap and stack&lt;/a&gt; that the JVM manages? Same idea. The stack is everywhere.&lt;/p&gt;

&lt;p&gt;The key constraint: you can only directly interact with the top. This feels limiting at first. We'll get there.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second: bytecode.&lt;/strong&gt; Instead of executing source code directly (like a scripting interpreter would), a bytecode VM compiles source code down into a compact binary representation — bytecode — and then interprets &lt;em&gt;that&lt;/em&gt;. Each byte is an instruction (or an argument to one). The VM reads them one at a time and figures out what to do. This is how CPython works. It's how the JVM works. It's how the Lua VM works.&lt;/p&gt;

&lt;p&gt;Put them together and you have a &lt;strong&gt;stack-based bytecode virtual machine&lt;/strong&gt; : a program that reads bytecode instructions and uses a stack to do all its work — no registers, no complex addressing modes. Push operands, execute an instruction, the result lands on the stack. Clean, portable, and surprisingly powerful.&lt;/p&gt;

&lt;p&gt;Now let's build it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Define Your Instruction Set
&lt;/h2&gt;

&lt;p&gt;The first thing any VM needs is an &lt;strong&gt;instruction set&lt;/strong&gt; — the vocabulary of operations it knows how to perform. Every opcode is just a number. We use C preprocessor macros to give them readable names:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;stdint.h&amp;gt;
#include &amp;lt;stdbool.h&amp;gt;

#define PUSH    0x00
#define PUSHP   0x01
#define POP     0x02
#define ADD     0x03
#define SUB     0x04
#define MUL     0x05
#define DIV     0x06
#define JMP     0x07
#define JNE     0x08
#define JE      0x09
#define JG      0x0A
#define DPRINT  0x0B
#define SPRINT  0x0C
#define DPRINTST 0x0D
#define DUP     0x0E
#define SWAP    0x0F
#define END     0x10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;17 instructions total. That's our entire universe for now. Let's break down each include before moving on, because they each earn their place here.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**stdio.h**&lt;/code&gt; — standard I/O. We need this for &lt;code&gt;printf&lt;/code&gt; to handle error messages, debug output, and printing strings from the VM. Every debug print in the execution loop runs through this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;stdlib.h&lt;/code&gt;&lt;/strong&gt; — standard library. Static arrays for the stack and constant pool live here. It's also your expansion point if you later want dynamic memory allocation.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**stdint.h**&lt;/code&gt; — this one matters most. When you're doing low-level work like building a VM, you need to guarantee integer sizes. &lt;code&gt;int32_t&lt;/code&gt; is always 32 bits. &lt;code&gt;int8_t&lt;/code&gt; is always 8 bits. No surprises across platforms. Without this, bytecode handling gets sketchy fast.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**stdbool.h**&lt;/code&gt; — gives us &lt;code&gt;bool&lt;/code&gt;, &lt;code&gt;true&lt;/code&gt;, and &lt;code&gt;false&lt;/code&gt;. We use a debug boolean flag throughout the VM to toggle verbose output without recompiling. Makes the code much more readable than throwing &lt;code&gt;int&lt;/code&gt; flags everywhere.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/custom-java-garbage-collector/" rel="noopener noreferrer"&gt;Implementing Your Own Garbage Collector in Java: Memory Allocation, Reference Tracking, and GC Algorithms&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  The Constant Pool and Helper Functions
&lt;/h2&gt;

&lt;p&gt;Here's a problem: our stack holds integers. What about strings? What about integers larger than 128? (That limit is a design choice we'll explain shortly.)&lt;/p&gt;

&lt;p&gt;The answer is a &lt;strong&gt;constant pool&lt;/strong&gt; — a shared storage area for values the stack can't hold directly. Think of it as the VM's read-only data segment.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct {
    int location; // index in the pool
    int type;
    union {
        char* Svalue;
        int   Ivalue;
    };
} const_t;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;union&lt;/code&gt; here is key. A &lt;code&gt;const_t&lt;/code&gt; entry holds &lt;em&gt;either&lt;/em&gt; a string (&lt;code&gt;Svalue&lt;/code&gt;) or an integer (&lt;code&gt;Ivalue&lt;/code&gt;), not both — and the &lt;code&gt;type&lt;/code&gt; field tells us which. This keeps entries compact without wasting memory on a full-size struct for every possible value.&lt;/p&gt;

&lt;p&gt;Now our push and pop helpers:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bool debug = false; // set to true for verbose execution traces

int push(int32_t* stack, int* sp, int value) {
    stack[*sp] = value;
    return (*sp)++;
}

int pop(int32_t* stack, int* sp) {
    if (*sp &amp;gt; 0) {
        (*sp)--;
        return stack[*sp];
    } else {
        printf("\e[0;31mError: Stack underflow\e[0;37m\n");
        if (debug) {
            for (int i = 0; i &amp;lt; *sp + 1; i++) {
                printf("%d ", stack[i]);
            }
        }
        return -1;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A few things worth noting here:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;push&lt;/code&gt; takes a pointer to the stack &lt;em&gt;and&lt;/em&gt; a pointer to the stack pointer (&lt;code&gt;sp&lt;/code&gt;). We do this so the same functions can work with multiple stacks if we ever need them — good API design even at this scale.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pop&lt;/code&gt; checks for stack underflow before doing anything. If &lt;code&gt;sp&lt;/code&gt; is already at 0, there's nothing to pop. We print an error in red (&lt;code&gt;\e[0;31m&lt;/code&gt;), dump the current stack state if debug mode is on, and return &lt;code&gt;-1&lt;/code&gt; as a sentinel. This kind of defensive check is what separates a toy VM from one that gives you useful errors when your bytecode is wrong.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initialize the Stack and Constant Pool
&lt;/h2&gt;

&lt;p&gt;Now we wire everything together with global state:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int32_t stack[256];
int sp = 0;
const_t pool[128];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The stack is a fixed-size array of 256 &lt;code&gt;int32_t&lt;/code&gt; values. The stack pointer &lt;code&gt;sp&lt;/code&gt; starts at 0 — the bottom. The constant pool holds up to 128 entries.&lt;/p&gt;

&lt;p&gt;This is also the reason &lt;code&gt;PUSH&lt;/code&gt; has a 128-value ceiling I mentioned earlier: we limit each PUSH argument to a single signed byte (&lt;code&gt;int8_t&lt;/code&gt;), which maxes out at 127. If you need to put a bigger integer on the stack, you define it in the pool and use &lt;code&gt;PUSHP&lt;/code&gt; (push from pool) instead. It's a deliberate design constraint that simplifies the instruction encoding at the cost of flexibility for large immediate values.&lt;/p&gt;

&lt;p&gt;One thing I learned the hard way while building this: a stack with &lt;em&gt;only&lt;/em&gt; top-of-stack access turns out to be insufficient for real programs. I discovered this when I tried implementing a Fibonacci number counter and it simply couldn't be done. After some research, I found out why — the VM was functionally equivalent to a &lt;a href="https://en.wikipedia.org/wiki/Pushdown_automaton" rel="noopener noreferrer"&gt;Pushdown Automaton&lt;/a&gt;, and pushdown automata can't compute Fibonacci sequences. They're not &lt;a href="https://en.wikipedia.org/wiki/Turing_completeness" rel="noopener noreferrer"&gt;Turing complete&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;That's why we have &lt;code&gt;SWAP&lt;/code&gt; in the instruction set. SWAP lets you exchange the top of the stack with an element at an arbitrary depth — giving you access to any stack slot, not just the top. Some VMs solve this differently by adding registers. We kept it purely stack-based and used SWAP instead. Either works; this was the simpler path.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Execution Loop
&lt;/h2&gt;

&lt;p&gt;This is the heart of the VM. Everything else is scaffolding around this.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void exec(int32_t* stack, int* sp, const_t* pool, int8_t* code, size_t size) {
    int pc = 0; // program counter

    if (debug)
        printf("Code is: %hhd, size is %lu\n", *code, sizeof(code));

    while (pc &amp;lt; size) {
        int opcode = code[pc];

        if (debug) {
            printf("Opcode: %d | PC: %d | SP: %d\n", opcode, pc, *sp);
            for (int i = 0; i &amp;lt; *sp; i++) {
                printf("%d ", stack[i]);
            }
            printf("\n");
        }

        if (*sp &amp;gt; 256) {
            printf("Stack overflow: SP=%d at opcode %d\n", *sp, opcode);
            return;
        }

        switch (opcode) {
            case SPRINT: {
                int b1 = code[++pc];
                int b2 = code[++pc];
                int idx = (b1 &amp;lt;&amp;lt; 8) | b2;
                const_t entry = pool[idx];
                printf("%s\n", entry.Svalue);
                pc++;
                break;
            }
            case END: {
                return;
            }
            default: {
                printf("\e[0;31mUnrecognized instruction at PC %d\e[0;37m\n", pc);
                pc++;
                break;
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's walk through this carefully, because there's a lot happening.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**int pc = 0**&lt;/code&gt; — the program counter. This is an index into the &lt;code&gt;code&lt;/code&gt; array. It tells the VM which instruction to execute next. Every time we process an instruction, we advance &lt;code&gt;pc&lt;/code&gt;. When &lt;code&gt;pc &amp;gt;= size&lt;/code&gt;, the program is done.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**while (pc &amp;lt; size)**&lt;/code&gt; — the main dispatch loop. This runs forever (until &lt;code&gt;END&lt;/code&gt; or until we fall off the end of the bytecode). Each iteration: read opcode, dispatch, advance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;int opcode = code[pc]&lt;/code&gt;&lt;/strong&gt; — read the current byte as an opcode. This is always the first thing we do. The opcode tells us which case in the switch to execute.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The debug block&lt;/strong&gt; — prints the current opcode, program counter, and stack pointer on every iteration, then dumps the entire stack. This is invaluable when your bytecode is misbehaving. Toggle it with &lt;code&gt;debug = true&lt;/code&gt; and you get a full execution trace.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack overflow check&lt;/strong&gt; — &lt;code&gt;if (*sp &amp;gt; 256)&lt;/code&gt; catches runaway pushes before they corrupt memory. We allocated 256 slots; writing past that is undefined behavior in C and will corrupt whatever lives next to the array in memory. Check early, fail loudly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;case SPRINT&lt;/code&gt;&lt;/strong&gt; — our first real instruction. SPRINT takes a 2-byte argument (16-bit index) pointing to a string in the constant pool:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;code[++pc]&lt;/code&gt; — advance &lt;code&gt;pc&lt;/code&gt; and read the high byte of the index&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;code[++pc]&lt;/code&gt; — advance &lt;code&gt;pc&lt;/code&gt; again and read the low byte&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;(b1 &amp;lt;&amp;lt; 8) | b2&lt;/code&gt; — reconstruct the 16-bit index from two bytes. &lt;code&gt;b1&lt;/code&gt; is the high byte, shifted left 8 positions; &lt;code&gt;b2&lt;/code&gt; is the low byte. OR them together and you've got your index.&lt;/li&gt;
&lt;li&gt;Fetch the pool entry, print its string, advance &lt;code&gt;pc&lt;/code&gt; once more to land on the next instruction.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why two bytes for the index? Because a single byte only gives us 256 pool entries maximum. Two bytes gives us 65,536 entries — more than enough headroom.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;case END&lt;/code&gt;&lt;/strong&gt; — terminates execution. Clean and simple.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**default**&lt;/code&gt; — instead of crashing on an unknown opcode, we print an error and advance &lt;code&gt;pc&lt;/code&gt;. This makes the VM &lt;em&gt;fault-resilient&lt;/em&gt; : bad instructions are logged but don't bring down the whole program. In practice this also means you could craft bytecode that does wildly different things on a second pass through the loop — an interesting property for anyone who wants to build self-modifying code experiments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does&lt;code&gt;exec&lt;/code&gt; take &lt;code&gt;size_t size&lt;/code&gt;?&lt;/strong&gt; Because when you pass a C array to a function, it decays to a pointer to its first element. Calling &lt;code&gt;sizeof()&lt;/code&gt; on that pointer gives you the size of a pointer (8 bytes on 64-bit systems) — not the size of the array. We have to pass the size explicitly. This is one of C's classic gotchas.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/jdk-27-new-features/" rel="noopener noreferrer"&gt;JDK 27 New Features Explained: What Actually Changes&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  The Main Function
&lt;/h2&gt;

&lt;p&gt;Now let's wire it all together.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main(int argc, char *argv[]) {
    // Populate the constant pool
    pool[0] = (const_t){0, 0, .Svalue = "Welcome to the Virtual Machine!"};

    // Define a simple program
    int8_t code[] = {
        SPRINT, 0x00, 0x00,
        END,
    };

    if (debug)
        printf("Size of code is %zu\n", sizeof(code));

    exec(stack, &amp;amp;sp, pool, code, sizeof(code));
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The bytecode here is four bytes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;SPRINT&lt;/code&gt; (&lt;code&gt;0x0C&lt;/code&gt;) — print a string from the pool&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;0x00, 0x00&lt;/code&gt; — pool index 0 (high byte 0, low byte 0)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;END&lt;/code&gt; (&lt;code&gt;0x10&lt;/code&gt;) — stop&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When &lt;code&gt;exec&lt;/code&gt; runs, it reads &lt;code&gt;SPRINT&lt;/code&gt;, fetches the two index bytes, looks up &lt;code&gt;pool[0]&lt;/code&gt;, prints &lt;code&gt;"Welcome to the Virtual Machine!"&lt;/code&gt;, then reads &lt;code&gt;END&lt;/code&gt; and returns. Done.&lt;/p&gt;

&lt;h2&gt;
  
  
  Building and Running
&lt;/h2&gt;

&lt;p&gt;Compile with GCC:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gcc -o vm main.c
./vm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You should see:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Welcome to the Virtual Machine!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it. A working VM executing real bytecode. Two instructions — but they're the two instructions that prove the entire architecture works.&lt;/p&gt;

&lt;h2&gt;
  
  
  What's Missing (And What's Next)
&lt;/h2&gt;

&lt;p&gt;We've got the shell. The loop, the stack, the constant pool, the instruction decoder — all of it is in place. The remaining 15 instructions are just more cases in the switch statement, each implementing specific behavior:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;PUSH&lt;/code&gt; / &lt;code&gt;PUSHP&lt;/code&gt; / &lt;code&gt;POP&lt;/code&gt; — stack manipulation&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ADD&lt;/code&gt; / &lt;code&gt;SUB&lt;/code&gt; / &lt;code&gt;MUL&lt;/code&gt; / &lt;code&gt;DIV&lt;/code&gt; — arithmetic&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;JMP&lt;/code&gt; / &lt;code&gt;JNE&lt;/code&gt; / &lt;code&gt;JE&lt;/code&gt; / &lt;code&gt;JG&lt;/code&gt; — jumps and branching (this is where control flow comes from)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;DPRINT&lt;/code&gt; / &lt;code&gt;DPRINTST&lt;/code&gt; — print integers and stack state&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;DUP&lt;/code&gt; — duplicate the top of the stack&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;SWAP&lt;/code&gt; — swap top with another stack element (our Turing-completeness fix)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The jump instructions are where things get genuinely interesting — they're what allows loops and conditionals, and they're also where most VM bugs live. We'll dig into all of them in Part 2.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Full Code
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
&lt;h1&gt;
  
  
  include &amp;lt;stdlib.h&amp;gt;
&lt;/h1&gt;
&lt;h1&gt;
  
  
  include &amp;lt;stdint.h&amp;gt;
&lt;/h1&gt;
&lt;h1&gt;
  
  
  include &amp;lt;stdbool.h&amp;gt;
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define PUSH     0x00
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define PUSHP    0x01
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define POP      0x02
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define ADD      0x03
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define SUB      0x04
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define MUL      0x05
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define DIV      0x06
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define JMP      0x07
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define JNE      0x08
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define JE       0x09
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define JG       0x0A
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define DPRINT   0x0B
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define SPRINT   0x0C
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define DPRINTST 0x0D
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define DUP      0x0E
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define SWAP     0x0F
&lt;/h1&gt;
&lt;h1&gt;
  
  
  define END      0x10
&lt;/h1&gt;

&lt;p&gt;bool debug = false;&lt;/p&gt;

&lt;p&gt;typedef struct {&lt;br&gt;
    int location;&lt;br&gt;
    int type;&lt;br&gt;
    union {&lt;br&gt;
        char* Svalue;&lt;br&gt;
        int   Ivalue;&lt;br&gt;
    };&lt;br&gt;
} const_t;&lt;/p&gt;

&lt;p&gt;int32_t stack[256];&lt;br&gt;
int sp = 0;&lt;br&gt;
const_t pool[128];&lt;/p&gt;

&lt;p&gt;int push(int32_t* stack, int* sp, int value) {&lt;br&gt;
    stack[*sp] = value;&lt;br&gt;
    return (*sp)++;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;int pop(int32_t* stack, int* sp) {&lt;br&gt;
    if (*sp &amp;gt; 0) {&lt;br&gt;
        (*sp)--;&lt;br&gt;
        return stack[*sp];&lt;br&gt;
    } else {&lt;br&gt;
        printf("\e[0;31mError: Stack underflow\e[0;37m\n");&lt;br&gt;
        if (debug) {&lt;br&gt;
            for (int i = 0; i &amp;lt; *sp + 1; i++) {&lt;br&gt;
                printf("%d ", stack[i]);&lt;br&gt;
            }&lt;br&gt;
        }&lt;br&gt;
        return -1;&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;void exec(int32_t* stack, int* sp, const_t* pool, int8_t* code, size_t size) {&lt;br&gt;
    int pc = 0;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (debug)
    printf("Code is: %hhd, size is %lu\n", *code, sizeof(code));

while (pc &amp;amp;lt; size) {
    int opcode = code[pc];

    if (debug) {
        printf("Opcode: %d | PC: %d | SP: %d\n", opcode, pc, *sp);
        for (int i = 0; i &amp;amp;lt; *sp; i++) {
            printf("%d ", stack[i]);
        }
        printf("\n");
    }

    if (*sp &amp;amp;gt; 256) {
        printf("Stack overflow: SP=%d at opcode %d\n", *sp, opcode);
        return;
    }

    switch (opcode) {
        case SPRINT: {
            int b1 = code[++pc];
            int b2 = code[++pc];
            int idx = (b1 &amp;amp;lt;&amp;amp;lt; 8) | b2;
            const_t entry = pool[idx];
            printf("%s\n", entry.Svalue);
            pc++;
            break;
        }
        case END: {
            return;
        }
        default: {
            printf("\e[0;31mUnrecognized instruction at PC %d\e[0;37m\n", pc);
            pc++;
            break;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;int main(int argc, char *argv[]) {&lt;br&gt;
    pool[0] = (const_t){0, 0, .Svalue = "Welcome to the Virtual Machine!"};&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int8_t code[] = {
    SPRINT, 0x00, 0x00,
    END,
};

if (debug)
    printf("Size of code is %zu\n", sizeof(code));

exec(stack, &amp;amp;amp;sp, pool, code, sizeof(code));
return 0;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  The Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;A stack-based bytecode VM is one of those things that looks intimidating from the outside and obvious once you've built one. The core is dead simple: a loop, an array, a program counter, and a switch statement. Everything else — arithmetic, jumps, function calls, string handling — is just more cases.&lt;/p&gt;

&lt;p&gt;The real lessons here aren't specific to VMs. They show up everywhere in low-level systems work: pass sizes explicitly when arrays decay to pointers, check your boundaries before you blow past them, make debug output a first-class citizen from day one, and choose your constraints deliberately (like our 128-value push limit) rather than discovering them as bugs.&lt;/p&gt;

&lt;p&gt;Part 2 will add arithmetic, stack manipulation, and the jump instructions — which is where this VM becomes genuinely useful. The jump instructions are also where most of the interesting bugs live, so that should be a good time.&lt;/p&gt;

&lt;p&gt;Compile it. Run it. Tweak the bytecode. Break it. That's how this stuff actually sticks.&lt;/p&gt;

&lt;p&gt;Related reading: &lt;a href="https://sudosecurity.org/getting-started-with-embedded-c/" rel="noopener noreferrer"&gt;Getting started with Embedded C&lt;/a&gt; and &lt;a href="https://sudosecurity.org/msvc-build-tools-preview-august-2026/" rel="noopener noreferrer"&gt;MSVC's August Preview Clears 40 Bug Reports and Preps ARM64 for LUTI2&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>c</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>The Complete Self-Hosted AI Stack for 2026</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Mon, 16 Nov 2026 14:02:48 +0000</pubDate>
      <link>https://dev.to/sudosecurity/the-complete-self-hosted-ai-stack-for-2026-4ghh</link>
      <guid>https://dev.to/sudosecurity/the-complete-self-hosted-ai-stack-for-2026-4ghh</guid>
      <description>&lt;p&gt;Most guides to self-hosted AI stop at &lt;code&gt;ollama run llama3&lt;/code&gt;. You get the model running, you have a terminal prompt, and the guide says congratulations. Then you try to use it seriously — share it with a teammate, hook it into your editor, run two models at once, or figure out why responses started getting weird — and you discover that Ollama alone is not a stack. It's one layer of a stack, and you've been building on bare concrete.&lt;/p&gt;

&lt;p&gt;A real local AI setup looks like the diagram above. Eight components working together, each solving a specific problem that no other component solves. Remove any one and you either lose a capability or you're running something that will fail quietly in ways that are hard to debug.&lt;/p&gt;

&lt;p&gt;This guide builds the full stack in three tiers. Tier 1 is the beginner setup: Ollama, Open WebUI, and Traefik. Thirty minutes, three containers, works immediately. Tier 2 adds LiteLLM as a proxy layer, Qdrant as a vector store for RAG, and Langfuse for observability. Tier 3 adds monitoring, multi-user authentication, and the configuration choices that make a shared team deployment trustworthy. Every tier ships with a complete, copy-pasteable Docker Compose file.&lt;/p&gt;

&lt;p&gt;Before you start: this guide assumes Docker and Docker Compose are installed. If they're not, the &lt;a href="https://sudosecurity.org/what-is-docker/" rel="noopener noreferrer"&gt;What is Docker&lt;/a&gt; primer covers the concepts, and the install section of the &lt;a href="https://sudosecurity.org/self-hosted-ai-agent-stack-n8n-flowise-qdrant-langfuse-docker-2026/" rel="noopener noreferrer"&gt;AI agent stack guide&lt;/a&gt; has the full installation steps for Ubuntu and Debian.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Does Each Component Actually Do?
&lt;/h2&gt;

&lt;p&gt;The architecture diagram shows the flow. Here's why every component exists and what breaks without it.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Is Ollama and Why Is It the Foundation?
&lt;/h3&gt;

&lt;p&gt;Ollama wraps llama.cpp — the high-performance C++ inference library — behind a clean REST API and a CLI. It handles GPU memory allocation, model layer distribution across devices, automatic quantization selection, and model storage as content-addressed layers. You pull a model the same way you pull a Docker image. Switch models in one command. The API is OpenAI-compatible, which means anything built for the OpenAI API works with Ollama without modification.&lt;/p&gt;

&lt;p&gt;What Ollama does not handle: multi-user auth, spend tracking, request routing across multiple model instances, fallback to cloud providers when the local model is slow or unavailable, and observability. Those gaps are why the rest of the stack exists.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://sudosecurity.org/run-local-llm-on-your-pc-complete-guide-2026/" rel="noopener noreferrer"&gt;local LLM complete guide&lt;/a&gt; covers Ollama installation, hardware requirements, model selection, and quantization in depth. Read it first if you're new to running local models. This guide treats Ollama as a configured dependency and focuses on everything that sits on top of it.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Is Open WebUI and Why Not Just Use the Terminal?
&lt;/h3&gt;

&lt;p&gt;Open WebUI is a self-hosted chat interface that connects to Ollama (and any other OpenAI-compatible backend). It gives you persistent conversation history, model switching without restarting anything, file uploads, image generation integration, Retrieval Augmented Generation (RAG) from your own documents, multi-user accounts with role-based access, and a web interface that works from any browser on your network.&lt;/p&gt;

&lt;p&gt;The terminal interface disappears when you close it. Open WebUI persists. Every conversation is stored. You can search your chat history. You can share a link to a specific chat with a teammate. You can upload a PDF and ask questions about it. The terminal is for testing. Open WebUI is for working.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Is LiteLLM and Why Does It Go Between Open WebUI and Ollama?
&lt;/h3&gt;

&lt;p&gt;LiteLLM exposes a unified OpenAI-compatible API in front of 100+ LLM providers, handles load balancing, fallback routing, virtual key management, rate limiting, and spend tracking — all in a single proxy container.&lt;/p&gt;

&lt;p&gt;Without LiteLLM, Open WebUI talks directly to Ollama. That works for a single user with one model. It breaks the moment you want to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Route slow or complex requests to a cloud model while fast/simple requests stay local&lt;/li&gt;
&lt;li&gt;Add a second Ollama instance (second GPU, second machine) and split load between them&lt;/li&gt;
&lt;li&gt;Set per-user or per-team spending limits across all models&lt;/li&gt;
&lt;li&gt;Give different users different model access without giving them all direct API access&lt;/li&gt;
&lt;li&gt;Log every request centrally for debugging and cost analysis&lt;/li&gt;
&lt;li&gt;Switch from Ollama to vLLM or a different inference backend without changing Open WebUI's config
LiteLLM handles all of this. Load balancing is built in: you configure round-robin, least-busy, usage-based, or latency-based routing across multiple API keys or providers. Fallbacks are declarative: if the primary model fails, LiteLLM automatically retries the next provider in the list with no changes to your application code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What Is a Vector Database and Why Does RAG Need One?
&lt;/h3&gt;

&lt;p&gt;RAG (Retrieval Augmented Generation) is the technique that lets an LLM answer questions about documents it wasn't trained on — your internal docs, your codebase, your notes, your company's knowledge base. The process: ingest documents, chunk them into pieces, generate embedding vectors for each chunk, store those vectors in a vector database, then at query time embed the user's question and search for the most semantically similar chunks to inject as context.&lt;/p&gt;

&lt;p&gt;A vector database stores these embedding vectors and makes similarity search fast. Qdrant is the right choice for this stack: purpose-built for vector search, has a REST API, supports payload filtering (search by semantic similarity AND filter by metadata), and handles collections that grow to millions of vectors without restructuring. Open WebUI's built-in RAG uses Qdrant when configured. So does every other serious RAG pipeline.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Does Traefik Do and Why Not Just Expose Ports?
&lt;/h3&gt;

&lt;p&gt;Traefik is a reverse proxy that sits in front of all your services. It handles TLS termination (HTTPS certificates from Let's Encrypt, automatically renewed), routes incoming requests to the right container, and provides authentication middleware. Without it, you'd either expose Open WebUI and LiteLLM on raw HTTP, manage certificates manually, or set up Nginx with static configuration files for each service.&lt;/p&gt;

&lt;p&gt;Traefik reads Docker labels. You add four labels to a service definition and it appears on a subdomain with a valid HTTPS certificate. No Nginx config files. No manual &lt;code&gt;certbot renew&lt;/code&gt; cron jobs. No static upstream blocks that break when container IPs change. Adding a new service is four label lines.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Does Langfuse Do and Why Do You Need Observability?
&lt;/h3&gt;

&lt;p&gt;Langfuse records every LLM interaction as a structured trace: the full prompt, the model and parameters, every tool call and its result, the response, token counts, and latency at each step. Without it, when your agent gives a wrong answer, you have no systematic way to find out why.&lt;/p&gt;

&lt;p&gt;LiteLLM integrates with Langfuse natively — set two environment variables and every request flowing through the proxy is automatically traced. You get dashboards showing which models are being used, which queries are failing, where latency is coming from, and what each model run actually cost. This is the difference between running an LLM stack and operating one.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/build-ai-coding-assistant-local-codebase-2026/" rel="noopener noreferrer"&gt;Build Your Own AI Coding Assistant With Access to Your Entire Codebase (2026)&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  How Do You Choose Between the Three Tiers?
&lt;/h2&gt;

&lt;p&gt;Before writing any configuration, match your situation to the right tier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tier 1: Beginner&lt;/strong&gt; — Solo developer or single user. You want local inference with a proper web UI instead of a terminal. You don't need multi-user access, cost tracking, or production-grade routing. You have one machine with one GPU. Setup time: 30 minutes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tier 2: Power User&lt;/strong&gt; — You've outgrown Tier 1 because you want to access the stack from multiple devices, you want RAG on your own documents, you want LiteLLM's routing so you can fall back to a cloud model when the local model is too slow for a task, or you want to understand what your stack is actually doing. Setup time: 90 minutes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tier 3: Small Team&lt;/strong&gt; — Two to fifteen people sharing a stack. You need user accounts, shared document collections, per-user spending limits, monitoring that tells you when something breaks, and the security configuration that makes it safe to put this behind a domain name and share it with people who aren't developers. Setup time: half a day.&lt;/p&gt;

&lt;p&gt;Elevated&lt;/p&gt;

&lt;p&gt;Want this stack on a server instead of your desk? An Elevated VPS from SudoSecurity gives it an always-on home with real support.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/elevated/vps/" rel="noopener noreferrer"&gt;See Elevated VPS plans →&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Tier 1: The Beginner Stack
&lt;/h2&gt;

&lt;p&gt;Three containers. Ollama for inference, Open WebUI for the chat interface, Traefik for HTTPS routing. This is the minimum setup that's actually comfortable to use daily.&lt;/p&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;A server or desktop with Docker installed&lt;/li&gt;
&lt;li&gt;A domain name with DNS access (for Traefik's Let's Encrypt certificates)&lt;/li&gt;
&lt;li&gt;Ollama installed on the host with at least one model pulled
If you're running on the same machine where Ollama is already installed (not in Docker), Traefik and Open WebUI can connect to it at &lt;code&gt;http://host.docker.internal:11434&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Directory Setup
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir -p /opt/ai-stack/traefik/certs
touch /opt/ai-stack/traefik/certs/acme.json
chmod 600 /opt/ai-stack/traefik/certs/acme.json

docker network create ai-proxy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Tier 1 Docker Compose
&lt;/h3&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /opt/ai-stack/docker-compose.yml
version: "3.9"

networks:
  ai-proxy:
    external: true

services:

  traefik:
    image: traefik:v3.1
    container_name: ai-traefik
    restart: unless-stopped
    networks:
      - ai-proxy
    ports:
      - "80:80"
      - "443:443"
    command:
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--providers.docker.network=ai-proxy"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.web.http.redirections.entrypoint.to=websecure"
      - "--entrypoints.web.http.redirections.entrypoint.scheme=https"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.le.acme.email=you@yourdomain.com"
      - "--certificatesresolvers.le.acme.storage=/certs/acme.json"
      - "--certificatesresolvers.le.acme.httpchallenge.entrypoint=web"
      - "--log.level=WARN"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /opt/ai-stack/traefik/certs:/certs

  open-webui:
    image: ghcr.io/open-webui/open-webui:main
    container_name: ai-open-webui
    restart: unless-stopped
    networks:
      - ai-proxy
    extra_hosts:
      - "host.docker.internal:host-gateway"
    volumes:
      - open_webui_data:/app/backend/data
    environment:
      OLLAMA_BASE_URL: http://host.docker.internal:11434
      WEBUI_SECRET_KEY: "CHANGE_THIS_generate_with_openssl_rand_hex_32"
      # Disable signup after creating your first account
      ENABLE_SIGNUP: "true"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.open-webui.rule=Host(`ai.yourdomain.com`)"
      - "traefik.http.routers.open-webui.entrypoints=websecure"
      - "traefik.http.routers.open-webui.tls.certresolver=le"
      - "traefik.http.services.open-webui.loadbalancer.server.port=8080"

volumes:
  open_webui_data:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Start it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd /opt/ai-stack
docker compose up -d

# Watch for certificate issuance
docker logs ai-traefik -f
# Look for: "Retrieving certificate" and "Certificate obtained successfully"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Navigate to &lt;code&gt;https://ai.yourdomain.com&lt;/code&gt;. Create your account on first load. Set &lt;code&gt;ENABLE_SIGNUP: "false"&lt;/code&gt; in the compose file immediately after and restart the container — otherwise anyone who can reach your domain can create an account.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Disable signups
sed -i 's/ENABLE_SIGNUP: "true"/ENABLE_SIGNUP: "false"/' docker-compose.yml
docker compose up -d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;




&lt;p&gt;&lt;strong&gt;We recommend reading&lt;/strong&gt; &lt;a href="https://sudosecurity.org/run-local-llm-on-your-pc-complete-guide-2026/" rel="noopener noreferrer"&gt;How to Run a Local LLM on Your PC in 2026 (Complete Guide)&lt;/a&gt; to continue reading our selection of content. The Tier 1 stack you just built needs Ollama running on the host with the right model pulled and the right GPU configuration. That guide covers every hardware tier, model selection, quantization settings, and the Ollama setup that powers everything above it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/run-local-llm-on-your-pc-complete-guide-2026/" rel="noopener noreferrer"&gt;https://sudosecurity.org/run-local-llm-on-your-pc-complete-guide-2026/&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Tier 2: The Power User Stack
&lt;/h2&gt;

&lt;p&gt;Tier 2 adds LiteLLM as the proxy layer between Open WebUI and your inference backends, Qdrant as the vector store for RAG, and Langfuse for tracing every request. This is where the stack becomes genuinely powerful.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Environment File
&lt;/h3&gt;

&lt;p&gt;Create &lt;code&gt;/opt/ai-stack/.env&lt;/code&gt;. Never commit this to version control.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generate secrets:
# openssl rand -hex 32  (for most fields)
# openssl rand -base64 32  (for Langfuse fields)

# ── Open WebUI ──────────────────────────────────────────────
WEBUI_SECRET_KEY=generate_with_openssl_rand_hex_32

# ── LiteLLM ─────────────────────────────────────────────────
LITELLM_MASTER_KEY=sk-generate_with_openssl_rand_hex_32
LITELLM_DB_PASSWORD=generate_strong_password

# Cloud providers (optional -- leave empty to use local only)
OPENAI_API_KEY=
ANTHROPIC_API_KEY=

# ── Qdrant ──────────────────────────────────────────────────
QDRANT_API_KEY=generate_with_openssl_rand_hex_32

# ── Langfuse ────────────────────────────────────────────────
LANGFUSE_SECRET_KEY=generate_with_openssl_rand_base64_32
LANGFUSE_NEXTAUTH_SECRET=generate_with_openssl_rand_base64_32
LANGFUSE_SALT=generate_with_openssl_rand_hex_64
LANGFUSE_ENCRYPTION_KEY=generate_with_openssl_rand_hex_64
LANGFUSE_DB_PASSWORD=generate_strong_password
CLICKHOUSE_PASSWORD=generate_strong_password
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Tier 2 Docker Compose
&lt;/h3&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /opt/ai-stack/docker-compose.yml
version: "3.9"

networks:
  ai-proxy:
    external: true
  ai-internal:
    driver: bridge

volumes:
  open_webui_data:
  qdrant_data:
  litellm_postgres_data:
  langfuse_postgres_data:
  clickhouse_data:
  clickhouse_logs:

services:

  # ── Traefik (same as Tier 1) ─────────────────────────────
  traefik:
    image: traefik:v3.1
    container_name: ai-traefik
    restart: unless-stopped
    networks:
      - ai-proxy
    ports:
      - "80:80"
      - "443:443"
    command:
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--providers.docker.network=ai-proxy"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.web.http.redirections.entrypoint.to=websecure"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.le.acme.email=you@yourdomain.com"
      - "--certificatesresolvers.le.acme.storage=/certs/acme.json"
      - "--certificatesresolvers.le.acme.httpchallenge.entrypoint=web"
      - "--log.level=WARN"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /opt/ai-stack/traefik/certs:/certs

  # ── PostgreSQL for LiteLLM ────────────────────────────────
  litellm-postgres:
    image: postgres:16-alpine
    container_name: ai-litellm-postgres
    restart: unless-stopped
    networks:
      - ai-internal
    environment:
      POSTGRES_DB: litellm
      POSTGRES_USER: litellm
      POSTGRES_PASSWORD: ${LITELLM_DB_PASSWORD}
    volumes:
      - litellm_postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U litellm -d litellm"]
      interval: 10s
      retries: 5

  # ── Redis for LiteLLM caching ────────────────────────────
  redis:
    image: redis:7-alpine
    container_name: ai-redis
    restart: unless-stopped
    networks:
      - ai-internal
    command: redis-server --maxmemory 512mb --maxmemory-policy allkeys-lru

  # ── LiteLLM Proxy ─────────────────────────────────────────
  litellm:
    image: ghcr.io/berriai/litellm:main-stable
    container_name: ai-litellm
    restart: unless-stopped
    networks:
      - ai-internal
      - ai-proxy
    extra_hosts:
      - "host.docker.internal:host-gateway"
    depends_on:
      litellm-postgres:
        condition: service_healthy
    volumes:
      - /opt/ai-stack/litellm/config.yaml:/app/config.yaml:ro
    environment:
      DATABASE_URL: postgresql://litellm:${LITELLM_DB_PASSWORD}@litellm-postgres:5432/litellm
      LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
      REDIS_HOST: redis
      REDIS_PORT: 6379
      # Cloud provider keys (passed through to backends when needed)
      OPENAI_API_KEY: ${OPENAI_API_KEY}
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
      # Langfuse tracing
      LANGFUSE_PUBLIC_KEY: "pk-lf-..."        # Fill after Langfuse is running
      LANGFUSE_SECRET_KEY: ${LANGFUSE_SECRET_KEY}
      LANGFUSE_HOST: http://langfuse-web:3000
    command: ["--config", "/app/config.yaml", "--port", "4000", "--detailed_debug"]
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.litellm.rule=Host(`llm.yourdomain.com`)"
      - "traefik.http.routers.litellm.entrypoints=websecure"
      - "traefik.http.routers.litellm.tls.certresolver=le"
      - "traefik.http.services.litellm.loadbalancer.server.port=4000"

  # ── Open WebUI ────────────────────────────────────────────
  open-webui:
    image: ghcr.io/open-webui/open-webui:main
    container_name: ai-open-webui
    restart: unless-stopped
    networks:
      - ai-internal
      - ai-proxy
    depends_on:
      - litellm
      - qdrant
    volumes:
      - open_webui_data:/app/backend/data
    environment:
      # Point at LiteLLM, not Ollama directly
      OPENAI_API_KEY: ${LITELLM_MASTER_KEY}
      OPENAI_API_BASE_URL: http://litellm:4000
      WEBUI_SECRET_KEY: ${WEBUI_SECRET_KEY}
      ENABLE_SIGNUP: "false"
      # RAG configuration
      RAG_EMBEDDING_ENGINE: ollama
      RAG_OLLAMA_BASE_URL: http://host.docker.internal:11434
      QDRANT_URI: http://qdrant:6333
      QDRANT_API_KEY: ${QDRANT_API_KEY}
      RAG_EMBEDDING_MODEL: nomic-embed-text
      CHUNK_SIZE: 1000
      CHUNK_OVERLAP: 100
    extra_hosts:
      - "host.docker.internal:host-gateway"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.open-webui.rule=Host(`ai.yourdomain.com`)"
      - "traefik.http.routers.open-webui.entrypoints=websecure"
      - "traefik.http.routers.open-webui.tls.certresolver=le"
      - "traefik.http.services.open-webui.loadbalancer.server.port=8080"

  # ── Qdrant ────────────────────────────────────────────────
  qdrant:
    image: qdrant/qdrant:latest
    container_name: ai-qdrant
    restart: unless-stopped
    networks:
      - ai-internal
    environment:
      QDRANT__SERVICE__API_KEY: ${QDRANT_API_KEY}
    volumes:
      - qdrant_data:/qdrant/storage
    # Internal only -- no external exposure

  # ── Langfuse PostgreSQL ───────────────────────────────────
  langfuse-postgres:
    image: postgres:16-alpine
    container_name: ai-langfuse-postgres
    restart: unless-stopped
    networks:
      - ai-internal
    environment:
      POSTGRES_DB: langfuse
      POSTGRES_USER: langfuse
      POSTGRES_PASSWORD: ${LANGFUSE_DB_PASSWORD}
    volumes:
      - langfuse_postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U langfuse -d langfuse"]
      interval: 10s
      retries: 5

  # ── ClickHouse (Langfuse trace storage) ──────────────────
  clickhouse:
    image: clickhouse/clickhouse-server:24.8-alpine
    container_name: ai-clickhouse
    restart: unless-stopped
    networks:
      - ai-internal
    environment:
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
    volumes:
      - clickhouse_data:/var/lib/clickhouse
      - clickhouse_logs:/var/log/clickhouse-server
    ulimits:
      nofile: { soft: 262144, hard: 262144 }
    healthcheck:
      test: ["CMD", "clickhouse-client", "--password", "${CLICKHOUSE_PASSWORD}", "--query", "SELECT 1"]
      interval: 10s
      retries: 5

  # ── Langfuse Web ──────────────────────────────────────────
  langfuse-web:
    image: langfuse/langfuse:3
    container_name: ai-langfuse-web
    restart: unless-stopped
    networks:
      - ai-internal
      - ai-proxy
    depends_on:
      langfuse-postgres:
        condition: service_healthy
      clickhouse:
        condition: service_healthy
    environment:
      DATABASE_URL: postgresql://langfuse:${LANGFUSE_DB_PASSWORD}@langfuse-postgres:5432/langfuse
      CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD}@clickhouse:8123
      NEXTAUTH_URL: https://traces.yourdomain.com
      NEXTAUTH_SECRET: ${LANGFUSE_NEXTAUTH_SECRET}
      SALT: ${LANGFUSE_SALT}
      ENCRYPTION_KEY: ${LANGFUSE_ENCRYPTION_KEY}
      TELEMETRY_ENABLED: "false"
      AUTH_DISABLE_SIGNUP: "false"  # Disable after first user
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.langfuse.rule=Host(`traces.yourdomain.com`)"
      - "traefik.http.routers.langfuse.entrypoints=websecure"
      - "traefik.http.routers.langfuse.tls.certresolver=le"
      - "traefik.http.services.langfuse.loadbalancer.server.port=3000"

  # ── Langfuse Worker ───────────────────────────────────────
  langfuse-worker:
    image: langfuse/langfuse-worker:3
    container_name: ai-langfuse-worker
    restart: unless-stopped
    networks:
      - ai-internal
    depends_on:
      langfuse-postgres:
        condition: service_healthy
      clickhouse:
        condition: service_healthy
    environment:
      DATABASE_URL: postgresql://langfuse:${LANGFUSE_DB_PASSWORD}@langfuse-postgres:5432/langfuse
      CLICKHOUSE_URL: http://default:${CLICKHOUSE_PASSWORD}@clickhouse:8123
      SALT: ${LANGFUSE_SALT}
      ENCRYPTION_KEY: ${LANGFUSE_ENCRYPTION_KEY}
      TELEMETRY_ENABLED: "false"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  LiteLLM Configuration File
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;config.yaml&lt;/code&gt; drives LiteLLM's routing logic. Create &lt;code&gt;/opt/ai-stack/litellm/config.yaml&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# /opt/ai-stack/litellm/config.yaml

model_list:
  # Primary: local Ollama models
  - model_name: qwen2.5:14b
    litellm_params:
      model: ollama/qwen2.5:14b
      api_base: http://host.docker.internal:11434
      stream: true

  - model_name: qwen2.5-coder:14b
    litellm_params:
      model: ollama/qwen2.5-coder:14b
      api_base: http://host.docker.internal:11434

  - model_name: deepseek-r1:14b
    litellm_params:
      model: ollama/deepseek-r1:14b
      api_base: http://host.docker.internal:11434

  # Embedding model (for RAG)
  - model_name: nomic-embed-text
    litellm_params:
      model: ollama/nomic-embed-text
      api_base: http://host.docker.internal:11434

  # Cloud fallbacks (only active when API keys are set)
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY

  - model_name: claude-sonnet
    litellm_params:
      model: anthropic/claude-sonnet-4-5
      api_key: os.environ/ANTHROPIC_API_KEY

  # Router group: smart auto-routing
  - model_name: auto
    model_info:
      mode: embeddings
    litellm_params:
      model: ollama/qwen2.5:14b
      api_base: http://host.docker.internal:11434

router_settings:
  # Route fast requests local, slow/complex requests to cloud
  routing_strategy: latency-based-routing
  fallbacks:
    - {"qwen2.5:14b": ["gpt-4o"]}
    - {"qwen2.5-coder:14b": ["claude-sonnet"]}

litellm_settings:
  # Semantic caching -- never pay twice for the same prompt
  cache: true
  cache_params:
    type: redis
    host: redis
    port: 6379
    ttl: 600  # Cache for 10 minutes

  # Send all traces to Langfuse automatically
  success_callback: ["langfuse"]
  failure_callback: ["langfuse"]

  # Drop params that local models don't support
  drop_params: true

  # Retry on failure before fallback
  num_retries: 2
  request_timeout: 120

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL

  # Virtual key management (requires PostgreSQL)
  store_model_in_db: true

  # UI for the LiteLLM admin panel
  ui_access_mode: all

  allow_user_auth: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  What the LiteLLM Config Actually Does
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;routing_strategy: latency-based-routing&lt;/code&gt;&lt;/strong&gt; tracks response time per model and routes to the fastest available option. If your local Qwen2.5 14B is crunching a previous request and latency spikes, LiteLLM shifts the next request to a different instance or cloud fallback. Invisible to the user.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**fallbacks**&lt;/code&gt; defines what happens when a model fails entirely (not just slow — actually errors). If &lt;code&gt;qwen2.5:14b&lt;/code&gt; returns a 503, the request automatically retries against &lt;code&gt;gpt-4o&lt;/code&gt;. This is the config that makes your stack resilient to inference failures. The user sees a slightly slower response; they never see an error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;cache: true&lt;/code&gt; with Redis&lt;/strong&gt; stores semantic embeddings of recent queries. If two users ask the same question within ten minutes, the second answer comes from the cache in milliseconds. The model never gets called for the second request. For common questions in a team context, this can cut your inference load by 30-50%.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;**drop_params: true**&lt;/code&gt; silently removes parameters that local Ollama models don't support (like &lt;code&gt;response_format: {"type": "json_schema"}&lt;/code&gt; which is an OpenAI-only feature). Without this, requests that work fine with cloud models fail with local ones because Open WebUI sometimes sends cloud-specific parameters.&lt;/p&gt;
&lt;h3&gt;
  
  
  Setting Up Langfuse After First Boot
&lt;/h3&gt;

&lt;p&gt;Navigate to &lt;code&gt;https://traces.yourdomain.com&lt;/code&gt; and create the first admin account. Then:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Get your API keys from Langfuse's UI: Settings → API Keys
# Copy the public key (pk-lf-...) and secret key (sk-lf-...)

# Update your .env
echo "LANGFUSE_PUBLIC_KEY=pk-lf-yourkeyhere" &amp;gt;&amp;gt; /opt/ai-stack/.env

# Update the LiteLLM service environment in docker-compose.yml
# Replace "pk-lf-..." with your actual public key

# Restart LiteLLM to pick up the new config
docker compose restart litellm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Within minutes, every request flowing through LiteLLM appears as a trace in Langfuse. Click any trace to see the full prompt, the model response, token counts, and latency breakdown. If a response was wrong, you'll see exactly what the model received and returned.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;We recommend reading&lt;/strong&gt; &lt;a href="https://sudosecurity.org/self-hosted-ai-agent-stack-n8n-flowise-qdrant-langfuse-docker-2026/" rel="noopener noreferrer"&gt;Build Your Own AI Agent Stack: The Complete Self-Hosted Guide for 2026&lt;/a&gt; to continue reading our selection of content. The Tier 2 stack you have now is the inference and interface layer. That guide builds the automation and orchestration layer on top of it — n8n workflows, Flowise agent builders, and multi-step RAG pipelines that turn your AI stack into something that actually does work for you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/self-hosted-ai-agent-stack-n8n-flowise-qdrant-langfuse-docker-2026/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fib3lkypwhsgma9wdd9sn.png" width="256" height="256"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Tier 3: The Small Team Stack
&lt;/h2&gt;

&lt;p&gt;Tier 3 adds three things: infrastructure monitoring with Prometheus and Grafana, production-grade access control with Open WebUI's organization and group permissions, and the security hardening that makes this safe to run for a team. The Docker Compose additions below build on the Tier 2 file.&lt;/p&gt;

&lt;h3&gt;
  
  
  Adding Prometheus and Grafana
&lt;/h3&gt;

&lt;p&gt;LiteLLM exposes Prometheus metrics at &lt;code&gt;/metrics&lt;/code&gt; when configured. Open WebUI doesn't have native metrics, but Node Exporter covers the host.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Add to docker-compose.yml

  prometheus:
    image: prom/prometheus:v2.52.0
    container_name: ai-prometheus
    restart: unless-stopped
    networks:
      - ai-internal
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"
      - "--storage.tsdb.retention.time=30d"
      - "--web.enable-lifecycle"
    volumes:
      - /opt/ai-stack/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - prometheus_data:/prometheus
    # Internal only -- access via Grafana

  grafana:
    image: grafana/grafana:11.0.0
    container_name: ai-grafana
    restart: unless-stopped
    networks:
      - ai-internal
      - ai-proxy
    depends_on:
      - prometheus
    environment:
      GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD}
      GF_ANALYTICS_REPORTING_ENABLED: "false"
      GF_SERVER_ROOT_URL: "https://grafana.yourdomain.com"
    volumes:
      - grafana_data:/var/lib/grafana
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.grafana.rule=Host(`grafana.yourdomain.com`)"
      - "traefik.http.routers.grafana.entrypoints=websecure"
      - "traefik.http.routers.grafana.tls.certresolver=le"
      - "traefik.http.services.grafana.loadbalancer.server.port=3000"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Create &lt;code&gt;/opt/ai-stack/prometheus/prometheus.yml&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'litellm'
    static_configs:
      - targets: ['litellm:4000']
    metrics_path: /metrics

  - job_name: 'qdrant'
    static_configs:
      - targets: ['qdrant:6333']
    metrics_path: /metrics

  - job_name: 'node'
    static_configs:
      - targets: ['host.docker.internal:9100']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The full Prometheus and Grafana setup — alert rules, dashboard configuration, and PromQL for the queries that actually matter — is in the &lt;a href="https://sudosecurity.org/prometheus-grafana-self-hosted-monitoring-complete-guide-2026/" rel="noopener noreferrer"&gt;Prometheus and Grafana complete guide&lt;/a&gt;. The setup above wires them in. That guide fills them with content.&lt;/p&gt;

&lt;h3&gt;
  
  
  Team Access Control in Open WebUI
&lt;/h3&gt;

&lt;p&gt;Open WebUI's permission model works at three levels: global defaults, workspaces, and individual user roles. For a small team:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Global settings (Admin Panel → Settings):&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Default user role: User (not Admin)
Enable model file uploads: Admin only
Enable community sharing: Disabled
Chat export: Enabled for all
Document upload for RAG: Enabled for all
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;User roles:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Admin:&lt;/strong&gt; Full access including model management, user management, and system settings. One or two people.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;User:&lt;/strong&gt; Can chat, use RAG, access models permitted by the admin. The default for everyone else.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pending:&lt;/strong&gt; New signups before approval. Use this if you want to vet users before they get access.
&lt;strong&gt;Model filtering:&lt;/strong&gt; In Admin Panel → Models, you can restrict which models are visible to non-admin users. If you have cloud fallback models configured in LiteLLM but don't want users to accidentally run expensive GPT-4o queries, hide those models from the UI for regular users.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Workspaces&lt;/strong&gt; (Admin Panel → Workspaces): Group users and share document collections within a workspace without exposing those documents to everyone. A team of ten with two separate projects can have separate document namespaces without separate Open WebUI instances.&lt;/p&gt;

&lt;h3&gt;
  
  
  Securing Remote Access
&lt;/h3&gt;

&lt;p&gt;For team access from outside the local network, you have two options. The simpler one: Tailscale. The more powerful one: Teleport.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tailscale:&lt;/strong&gt; Every team member installs Tailscale, joins the same tailnet, and connects to Open WebUI via the internal Tailscale IP. No public-facing domain needed. Works in minutes. Fine for small teams with technical members.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Teleport:&lt;/strong&gt; Puts every service behind hardware-MFA-required, zero-trust access control. Every access attempt is logged, audited, and tied to a specific user identity. Short-lived certificates instead of passwords. The &lt;a href="https://sudosecurity.org/teleport-self-hosted-zero-trust-infrastructure-access-complete-guide-2026/" rel="noopener noreferrer"&gt;Teleport self-hosted guide&lt;/a&gt; covers the full setup. At SudoSecurity, we proxy Open WebUI through Teleport rather than exposing it directly — the access log alone is worth the setup time.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/self-hosting-openclaw-vps-setup-security-production-guide/" rel="noopener noreferrer"&gt;Self-Host OpenClaw: VPS Setup to Production (2026)&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  How Do You Tune Performance Across the Stack?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Ollama: VRAM Allocation and Context Windows
&lt;/h3&gt;

&lt;p&gt;The single biggest performance lever is keeping your model entirely in VRAM. A model that spills from VRAM into system RAM runs at 20-30% of its VRAM-only speed.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Check what's loaded and where
ollama ps

# Output:
# NAME               ID        SIZE    PROCESSOR    UNTIL
# qwen2.5:14b        ...       9.1 GB  100% GPU     4 min
#                                       ^^^^^^^^^^^
# "100% GPU" = entirely in VRAM. Good.
# "76%/24% CPU" = spilling. Load a smaller model.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Context window size directly affects VRAM usage. The default is 4096 tokens. Setting it to 32768 uses roughly 50% more VRAM for the same model. Set context size explicitly rather than relying on the default:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Set context size for a specific model via Ollama's REST API
curl http://localhost:11434/api/generate -d '{
  "model": "qwen2.5:14b",
  "options": {"num_ctx": 8192}
}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Or configure it in Open WebUI's model settings per-model.&lt;/p&gt;

&lt;h3&gt;
  
  
  LiteLLM: Connection Pooling and Worker Counts
&lt;/h3&gt;

&lt;p&gt;LiteLLM defaults are conservative. For a team deployment under regular load:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# In your litellm config.yaml
litellm_settings:
  # Increase concurrent request handling
  max_parallel_requests: 100

  # Aggressive timeout to fail fast to fallback
  request_timeout: 60

  # Keep connections to Ollama warm
  num_retries: 1        # Try once, fall back quickly



# In docker-compose.yml, LiteLLM service
command: &amp;gt;
  --config /app/config.yaml
  --port 4000
  --workers 4           # One worker per CPU core available to the container
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Qdrant: Collection Optimization
&lt;/h3&gt;

&lt;p&gt;Default Qdrant settings work for small collections. For a knowledge base with 100,000+ chunks, enable HNSW indexing optimization:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Update the collection configuration after initial creation
curl -X PATCH "http://localhost:6333/collections/your_collection" \
  -H "Content-Type: application/json" \
  -H "api-key: ${QDRANT_API_KEY}" \
  -d '{
    "optimizers_config": {
      "default_segment_number": 4,
      "indexing_threshold": 20000
    },
    "hnsw_config": {
      "m": 16,
      "ef_construct": 100,
      "full_scan_threshold": 10000
    }
  }'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;hnsw_config&lt;/code&gt; settings trade index build time for query speed. Higher &lt;code&gt;m&lt;/code&gt; and &lt;code&gt;ef_construct&lt;/code&gt; values give better recall accuracy at the cost of more memory and slower index builds. For a static knowledge base, build the index overnight and query it fast during the day. For a frequently updated collection, use the defaults.&lt;/p&gt;

&lt;h3&gt;
  
  
  Open WebUI: RAG Chunk Tuning
&lt;/h3&gt;

&lt;p&gt;The default chunk size (1000 tokens) and overlap (100 tokens) work for most prose documents. For technical documentation with lots of code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CHUNK_SIZE: 1500
CHUNK_OVERLAP: 200
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For short-form documents (emails, Slack messages, notes):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CHUNK_SIZE: 500
CHUNK_OVERLAP: 50
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The right chunk size is the one where the model's retrieved context contains the complete answer to a typical query without including irrelevant surrounding text. Test by asking questions you know the answer to and checking whether the retrieved chunks include the right information.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Security Mistakes Does Every Stack Make at First?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Exposing Services That Should Be Internal
&lt;/h3&gt;

&lt;p&gt;The most common mistake: adding Traefik labels to services that have no reason to be publicly accessible. Qdrant, Redis, LiteLLM's internal metrics endpoint, and Langfuse's worker process do not need Traefik routing. If they have a label, they're reachable.&lt;/p&gt;

&lt;p&gt;Correct pattern: services get Traefik labels only if humans need direct browser access. Everything else stays on &lt;code&gt;ai-internal&lt;/code&gt; with no external routing.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Audit which services are exposed
docker inspect $(docker compose ps -q) | \
  jq '.[] | select(.Labels."traefik.enable"=="true") | .Name'

# Should only show: open-webui, langfuse-web, grafana
# Should NOT show: qdrant, redis, litellm-postgres, clickhouse
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  LiteLLM Master Key Exposure
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;LITELLM_MASTER_KEY&lt;/code&gt; gives full admin access to LiteLLM's API. Never put it in the &lt;code&gt;OPENAI_API_KEY&lt;/code&gt; field of your IDE or code. Create virtual keys for different use cases:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a virtual key with budget limit for a specific user
curl -X POST "https://llm.yourdomain.com/key/generate" \
  -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "models": ["qwen2.5:14b", "qwen2.5-coder:14b"],
    "max_budget": 10.0,
    "budget_duration": "30d",
    "metadata": {"user": "alice", "team": "engineering"},
    "aliases": {"qwen2.5:14b": "local-main"}
  }'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This returns a virtual key (&lt;code&gt;sk-...&lt;/code&gt;) that Alice can use in her IDE. It can only access the two listed models, has a $10 monthly budget cap, and her usage is tracked separately in the Langfuse dashboard. The master key stays in your &lt;code&gt;.env&lt;/code&gt; and never touches a developer's machine.&lt;/p&gt;

&lt;h3&gt;
  
  
  Open WebUI's Default Cookie Settings
&lt;/h3&gt;

&lt;p&gt;Open WebUI's session cookies default to non-secure settings in some configurations. Verify in the admin panel that &lt;code&gt;WEBUI_SESSION_COOKIE_SECURE=true&lt;/code&gt; is set when serving over HTTPS. This prevents session cookie theft over non-HTTPS connections.&lt;/p&gt;

&lt;h3&gt;
  
  
  Qdrant Without Authentication
&lt;/h3&gt;

&lt;p&gt;Qdrant's default configuration runs with no authentication. The &lt;code&gt;QDRANT__SERVICE__API_KEY&lt;/code&gt; environment variable enables API key validation. Without it, anyone who can reach the Qdrant port can read, write, and delete every collection. The &lt;code&gt;ai-internal&lt;/code&gt; network isolation provides one layer of protection. The API key provides the second.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Do You Upgrade Components Without Downtime?
&lt;/h2&gt;

&lt;p&gt;The stack separates concerns cleanly, which means most components can be upgraded independently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open WebUI&lt;/strong&gt; (ships frequently, usually safe to update):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker compose pull open-webui
docker compose up -d --no-deps open-webui
# --no-deps prevents restarting unrelated services
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;LiteLLM&lt;/strong&gt; (check release notes before upgrading -- config format changes occasionally):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Test the new config format in a separate container first
docker run --rm \
  -v /opt/ai-stack/litellm/config.yaml:/app/config.yaml \
  ghcr.io/berriai/litellm:v1.91.0-stable \
  --config /app/config.yaml --test_connection

# If it passes, upgrade
docker compose pull litellm
docker compose up -d --no-deps litellm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Langfuse&lt;/strong&gt; (requires coordinated update of web + worker):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker compose pull langfuse-web langfuse-worker
docker compose up -d --no-deps langfuse-web langfuse-worker
# Both use the same image version -- always update together
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Qdrant&lt;/strong&gt; (data format changes happen between major versions -- read the changelog):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Back up first
docker exec ai-qdrant tar -czf /tmp/qdrant-backup.tar.gz /qdrant/storage
docker cp ai-qdrant:/tmp/qdrant-backup.tar.gz /opt/ai-stack/backups/

# Then upgrade
docker compose pull qdrant
docker compose up -d --no-deps qdrant
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  How Do You Back Up the Stack?
&lt;/h2&gt;

&lt;p&gt;Each component has data that matters:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Data Location&lt;/th&gt;
&lt;th&gt;Backup Priority&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Open WebUI&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;open_webui_data&lt;/code&gt; Docker volume&lt;/td&gt;
&lt;td&gt;High (chat history, user accounts)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;LiteLLM PostgreSQL&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;litellm_postgres_data&lt;/code&gt; volume&lt;/td&gt;
&lt;td&gt;Medium (virtual keys, spend data)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Qdrant&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;qdrant_data&lt;/code&gt; volume&lt;/td&gt;
&lt;td&gt;High if RAG knowledge base has custom documents&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Langfuse PostgreSQL&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;langfuse_postgres_data&lt;/code&gt; volume&lt;/td&gt;
&lt;td&gt;Medium (project config, user accounts)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ClickHouse&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;clickhouse_data&lt;/code&gt; volume&lt;/td&gt;
&lt;td&gt;Low (traces are re-generated; can accept loss)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Here is the backup script we created.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/bin/bash
# /opt/ai-stack/backup.sh

BACKUP_DATE=$(date +%Y%m%d-%H%M)
BACKUP_DIR="/opt/backups/ai-stack/${BACKUP_DATE}"
mkdir -p "${BACKUP_DIR}"

# Dump Open WebUI SQLite database
docker exec ai-open-webui sqlite3 /app/backend/data/webui.db \
  ".backup /tmp/webui-backup.db"
docker cp ai-open-webui:/tmp/webui-backup.db "${BACKUP_DIR}/webui.db"

# Dump LiteLLM PostgreSQL
docker exec ai-litellm-postgres pg_dump -U litellm litellm | \
  gzip &amp;gt; "${BACKUP_DIR}/litellm-postgres.sql.gz"

# Dump Langfuse PostgreSQL
docker exec ai-langfuse-postgres pg_dump -U langfuse langfuse | \
  gzip &amp;gt; "${BACKUP_DIR}/langfuse-postgres.sql.gz"

# Snapshot Qdrant collections
docker exec ai-qdrant curl -s \
  -X POST "http://localhost:6333/collections/knowledge_base/snapshots" \
  -H "api-key: ${QDRANT_API_KEY}"

# Compress everything
tar -czf "/opt/backups/ai-stack-${BACKUP_DATE}.tar.gz" "${BACKUP_DIR}/"
rm -rf "${BACKUP_DIR}"

# Sync offsite
rsync -avz "/opt/backups/ai-stack-${BACKUP_DATE}.tar.gz" \
  "backup-server:/backups/ai-stack/"

# Clean up local backups older than 14 days
find /opt/backups -name "ai-stack-*.tar.gz" -mtime +14 -delete

echo "Backup complete: ai-stack-${BACKUP_DATE}.tar.gz"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;




&lt;p&gt;The stack described here is the one SudoSecurity runs internally for research and content work. Tier 1 took thirty minutes. Tier 2 took an afternoon. Tier 3 accumulated over several months as the team grew and monitoring gaps became visible.&lt;/p&gt;

&lt;p&gt;The key principle: each tier adds components that solve real problems the previous tier has. Add LiteLLM when you want routing and cost visibility, not before. Add Langfuse when you want to understand why responses are wrong. Add monitoring when you want to know before a user tells you that something broke.&lt;/p&gt;

&lt;p&gt;For the self-hosting ecosystem beyond the AI stack — the file storage, password manager, email, and media server that round out a complete self-hosted setup — the &lt;a href="https://sudosecurity.org/self-hosted-productivity-stack-nextcloud-vaultwarden-immich-jellyfin-paperless-2026/" rel="noopener noreferrer"&gt;SudoSecurity self-hosted productivity guide&lt;/a&gt; covers that full picture. For every sysadmin and AI article across the site, the &lt;a href="https://sudosecurity.org/linux/" rel="noopener noreferrer"&gt;SysAdmin section&lt;/a&gt; and the &lt;a href="https://sudosecurity.org/ai/" rel="noopener noreferrer"&gt;AI section&lt;/a&gt; are the places to start.&lt;/p&gt;

</description>
      <category>selfhosted</category>
      <category>ai</category>
      <category>docker</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>What You Can Self-Host on Oracle Cloud Free Tier (2026)</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Fri, 13 Nov 2026 05:39:14 +0000</pubDate>
      <link>https://dev.to/sudosecurity/what-you-can-self-host-on-oracle-cloud-free-tier-2026-3gfd</link>
      <guid>https://dev.to/sudosecurity/what-you-can-self-host-on-oracle-cloud-free-tier-2026-3gfd</guid>
      <description>&lt;p&gt;&lt;em&gt;Last updated: July 27, 2026&lt;/em&gt;  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Status as of this writing:&lt;/strong&gt; Oracle quietly cut the Always Free Ampere A1 allocation from 4 OCPUs / 24 GB RAM to 2 OCPUs / 12 GB RAM on June 15, 2026. No blog post, no email, an edited documentation page and nothing else. If you're reading an older guide (including some still-circulating 2026 posts) that budgets against 24 GB, check your own console before following its numbers. Everything below is sized for the current 2 OCPU / 12 GB reality, plus the two small AMD Micro instances that are unaffected by the change.&lt;/p&gt;

&lt;p&gt;A free tier that quietly loses half its headroom is still worth building on. It means the sizing conversation matters more than it used to, and CPU, not RAM, ends up being the tighter constraint on two cores.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Oracle gives you for free
&lt;/h2&gt;

&lt;p&gt;The Always Free resources relevant to a self-hosting stack:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Ampere A1 Flex (ARM):&lt;/strong&gt; 2 OCPUs and 12 GB RAM total, split across one to four instances as you choose. This is down from 4/24 as of June 2026.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;AMD Micro instances:&lt;/strong&gt; two of them, each 1/8 OCPU and 1 GB RAM. Small, but free on its own terms and separate from the Ampere allocation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Block storage:&lt;/strong&gt; 200 GB total, shared across your instances.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Outbound bandwidth:&lt;/strong&gt; 10 TB per month.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reclamation risk:&lt;/strong&gt; Oracle's current published policy reclaims an Always Free compute instance if, over a 7-day period, its 95th-percentile CPU, network, and (for A1 shapes) memory utilization all stay under 20%. A stack that's serving real traffic rarely trips this; an instance you spun up once and forgot about is exactly what the policy targets.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Regional availability:&lt;/strong&gt; Ampere A1 capacity is tightly constrained in popular regions. Frankfurt and Singapore tend to provision within minutes; US regions can sit at "out of host capacity" for hours or days. Budget for that when you're planning a migration deadline.
&lt;strong&gt;What "2 OCPU" means on Ampere A1.&lt;/strong&gt; On Oracle's x86 shapes, one OCPU is a full physical core with hyperthreading, billed as the equivalent of two vCPUs, so a workload can lean on simultaneous multithreading to squeeze more out of contended cores. Ampere A1 doesn't work that way: the Ampere Altra processor behind it has no hyperthreading, so one OCPU is exactly one physical core and one thread, nothing shared. Two OCPUs on this tier means two real cores and nothing more to borrow from. That's why CPU contention shows up immediately on this tier rather than being smoothed over by a hyperthreading scheduler the way it might be on an equivalent x86 box.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two honest limitations before the stack: first, ARM64 isn't universal. Most actively maintained self-hosting images ship multi-arch builds, but some don't. Ghost's core image runs fine on ARM64; its optional ActivityPub and Traffic Analyzer add-ons are AMD64-only as of this writing, so check before assuming a feature works. Second, 2 shared OCPUs is a real ceiling once more than one service wants the CPU at the same time. RAM sizing matters, but CPU contention is what bites on this tier.&lt;/p&gt;

&lt;h2&gt;
  
  
  The stack: one Ampere instance, one AMD Micro
&lt;/h2&gt;

&lt;p&gt;Put everything internet-facing on the single Ampere A1 instance, and use one AMD Micro purely as an external watchdog, something that checks whether the main box is reachable from outside its own failure domain. The second Micro is spare capacity for later.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Service&lt;/th&gt;
&lt;th&gt;Job&lt;/th&gt;
&lt;th&gt;Real RAM cost&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Caddy&lt;/td&gt;
&lt;td&gt;TLS termination, reverse proxy&lt;/td&gt;
&lt;td&gt;Under 50 MB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ghost + MySQL&lt;/td&gt;
&lt;td&gt;Blog/CMS (this article's own platform)&lt;/td&gt;
&lt;td&gt;Roughly 750 MB in production use&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Vaultwarden&lt;/td&gt;
&lt;td&gt;Password manager, Bitwarden-compatible&lt;/td&gt;
&lt;td&gt;~10 MB idle&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Syncthing&lt;/td&gt;
&lt;td&gt;Peer-to-peer file sync, no central server needed&lt;/td&gt;
&lt;td&gt;150–300 MB typical, spikes higher during large scans&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ollama (3B model, Q4)&lt;/td&gt;
&lt;td&gt;Lightweight local AI for personal use&lt;/td&gt;
&lt;td&gt;Roughly 3–4 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Uptime Kuma + Beszel agent&lt;/td&gt;
&lt;td&gt;Uptime checks plus host/container metrics&lt;/td&gt;
&lt;td&gt;150–180 MB combined&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;OS + Docker overhead&lt;/td&gt;
&lt;td&gt;Everything else&lt;/td&gt;
&lt;td&gt;Roughly 500 MB&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;That totals somewhere around 5–6 GB of the 12 GB available, leaving real headroom rather than a stack that fits with nothing to spare. The number that won't show up in a RAM table is CPU: an AI response generating tokens, a MySQL query, and a Syncthing hash scan happening at the same moment are competing for two cores, and that's where a personal Oracle box slows down, not memory pressure.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Running Vaultwarden already and want the full hardening pass?&lt;/strong&gt; Our dedicated Vaultwarden guide covers backup strategy, admin panel lockdown, and the HTTPS requirements the official clients enforce. &lt;a href="https://sudosecurity.org/self-hosting-vaultwarden/" rel="noopener noreferrer"&gt;Take a look at our complete Vaultwarden self-hosting guide&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/self-hosting-vaultwarden/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fib3lkypwhsgma9wdd9sn.png" width="256" height="256"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/oracle-free-tier-arm-cutoff-2026/" rel="noopener noreferrer"&gt;Oracle Free Tier ARM Cutoff: What to Do Before Aug 18&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Why each piece is on this list
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Ghost&lt;/strong&gt; runs the blog you're reading right now, so it earns a place as a real-world example rather than a theoretical pick. The official minimum is 1 GB of RAM; in production with MySQL running alongside it, a well-known self-hosting write-up clocks its own long-running instance at 214 MB for Ghost and 538 MB for MySQL, comfortably under 1 GB combined. Budget for 2 GB if you expect real traffic or plan to turn on the newsletter feature, which adds Mailgun and additional background jobs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vaultwarden&lt;/strong&gt; is the easiest sizing decision in this list. It's a Rust reimplementation of the Bitwarden server, and our own Vaultwarden instance (the one covered in our dedicated guide) idles around 10 MB of RAM serving eight active users, less than a browser tab. There's no meaningful tradeoff here: it's compatible with every official Bitwarden client, and the resource cost rounds to zero next to everything else on this instance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syncthing&lt;/strong&gt; covers file synchronization without needing a central server the way Nextcloud does; it syncs directly between your devices and this instance acts as one more always-on peer. That's a deliberate tradeoff for this tier: Nextcloud gets you a web UI, calendar and contacts sync, and a proper multi-user file store, all of which cost meaningfully more RAM than 12 GB comfortably supports alongside everything else here. If you have RAM to spare on a bigger box later, our &lt;a href="https://sudosecurity.org/self-hosted-productivity-stack-nextcloud-vaultwarden-immich-jellyfin-paperless-2026/" rel="noopener noreferrer"&gt;productivity-stack guide&lt;/a&gt; covers Nextcloud, Immich, Jellyfin, and Paperless-ngx together. On this tier, Syncthing does the one job (getting files onto more than one device) for a fraction of the cost.&lt;/p&gt;

&lt;p&gt;Idle RAM use is modest, but it's not flat: Syncthing keeps file indexes in memory, and both very large individual files and folders with hundreds of thousands of small files can push memory use well above idle during an initial scan, in some reported cases into the gigabytes on a large enough folder tree. If you're syncing a large photo library or a folder with a huge file count, set &lt;code&gt;maxConcurrentWrites&lt;/code&gt; to 1 and sync folders sequentially rather than in parallel; both are documented tuning options that trade sync speed for a lower peak. On a 12 GB instance already running an AI model, that peak matters more than it would on a dedicated NAS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ollama&lt;/strong&gt; is the one service constrained by this tier's hardware and not only its RAM budget. There's no GPU on Oracle's free tier at all, so inference runs on the Ampere A1's ARM cores. A quantized 7B model is technically possible (public benchmarks put a Q4_K_M 7B model around 5–8 tokens per second on a 4-OCPU A1 instance), but at 2 OCPUs, a smaller 3B model at Q4 quantization is the more honest fit for anything resembling a responsive personal assistant, and it leaves the other two-thirds of your CPU budget for Ghost and Syncthing to use.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Uptime Kuma paired with Beszel&lt;/strong&gt; is the monitoring choice that matters most on a RAM-constrained tier. A combined Prometheus, Grafana, and node_exporter stack, the setup in our &lt;a href="https://sudosecurity.org/prometheus-grafana-self-hosted-monitoring-complete-guide-2026/" rel="noopener noreferrer"&gt;own monitoring guide&lt;/a&gt;, runs 800 MB or more at idle before it's watched a single request; Uptime Kuma plus a Beszel agent covers external uptime checks and internal host/container metrics for roughly 150–180 MB combined. On a 24 GB instance, or a paid box with RAM to spare, Prometheus and Grafana's deeper PromQL querying and alerting rules are worth the extra memory. On 12 GB shared with an AI model, Uptime Kuma is the choice between having monitoring at all and not.&lt;/p&gt;

&lt;p&gt;Elevated&lt;/p&gt;

&lt;p&gt;Outgrown the free tier, or tired of Oracle reclaiming idle instances? Elevated runs managed VPS hosting from SudoSecurity, with real support behind it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/elevated/vps/" rel="noopener noreferrer"&gt;See Elevated VPS plans →&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Layout
&lt;/h2&gt;

&lt;p&gt;Oracle free tier architecture · SVG  Oracle Free Tier: Two-Instance Layout Ampere A1 Flex -- 2 OCPU / 12 GB RAM (Always Free) Caddy (TLS, reverse proxy) -- &amp;lt;50 MB Ghost + MySQL -- ~750 MB Vaultwarden -- ~50 MB Syncthing -- ~150-300 MB Ollama, 3B model Q4 -- ~3-4 GB Uptime Kuma + Beszel agent -- ~150-180 MB OS + Docker overhead -- ~500 MB Remaining headroom: roughly 6-7 GB of 12 GB Shared constraint: 2 OCPU total AI inference, MySQL queries, and Syncthing hashing compete for the same 2 cores -- CPU, not RAM, is the real ceiling on this tier AMD Micro -- 1/8 OCPU 1 GB RAM (Always Free) External uptime check Watches the Ampere box from outside its own failure domain Internet-facing CPU-heaviest service&lt;/p&gt;

&lt;p&gt;Everything internet-facing sits behind Caddy on the Ampere instance. The AMD Micro doesn't run any of the stack; its only job is checking the Ampere box from a separate failure domain, so a problem with the main instance doesn't also take down the thing telling you about the problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  A resource-bounded Compose file
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services:
  caddy:
    image: caddy:latest
    restart: unless-stopped
    ports:
      - "443:443"
      - "80:80"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
    networks:
      - stack_net

  ghost:
    image: ghost:5
    restart: unless-stopped
    environment:
      - database__client=mysql
      - database__connection__host=ghost-db
      - database__connection__user=ghost
      - database__connection__password=${GHOST_DB_PASSWORD}
      - database__connection__database=ghost
      - url=https://blog.yourdomain.com
    volumes:
      - ghost_content:/var/lib/ghost/content
    deploy:
      resources:
        limits:
          memory: 1g
    networks:
      - stack_net

  ghost-db:
    image: mysql:8
    restart: unless-stopped
    environment:
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
      - MYSQL_DATABASE=ghost
      - MYSQL_USER=ghost
      - MYSQL_PASSWORD=${GHOST_DB_PASSWORD}
    volumes:
      - ghost_db:/var/lib/mysql
    deploy:
      resources:
        limits:
          memory: 700m
    networks:
      - stack_net

  vaultwarden:
    image: vaultwarden/server:latest
    restart: unless-stopped
    environment:
      - ADMIN_TOKEN=${VAULTWARDEN_ADMIN_TOKEN}
      - SIGNUPS_ALLOWED=false
    volumes:
      - vaultwarden_data:/data
    deploy:
      resources:
        limits:
          memory: 128m
    networks:
      - stack_net

  syncthing:
    image: syncthing/syncthing:latest
    restart: unless-stopped
    environment:
      - STMAXCONCURRENTWRITES=1
    volumes:
      - syncthing_data:/var/syncthing
    deploy:
      resources:
        limits:
          memory: 768m
    networks:
      - stack_net

  ollama:
    image: ollama/ollama:latest
    restart: unless-stopped
    volumes:
      - ollama_data:/root/.ollama
    deploy:
      resources:
        limits:
          memory: 4g
    networks:
      - stack_net

  uptime-kuma:
    image: louislam/uptime-kuma:2
    restart: unless-stopped
    volumes:
      - uptime_kuma_data:/app/data
    deploy:
      resources:
        limits:
          memory: 150m
    networks:
      - stack_net

networks:
  stack_net:
    external: true

volumes:
  caddy_data:
  ghost_content:
  ghost_db:
  vaultwarden_data:
  syncthing_data:
  ollama_data:
  uptime_kuma_data:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Caddy stays the only exposed port on the instance. Everything else, Ghost, Vaultwarden, Syncthing's sync protocol, Ollama's API, and the Uptime Kuma dashboard, sits behind it on the internal Docker network, reachable by subdomain rather than by port number.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/how-to-self-host-a-discord-bot-building-and-running-your-own-bot-24-7/" rel="noopener noreferrer"&gt;How to Self-Host a Discord Bot: Building and Running Your Own Bot 24/7&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Three Important Performance Fixes
&lt;/h2&gt;

&lt;p&gt;The Compose file above will run. These three changes are what keep it running well once Syncthing hits a big scan or Ollama is mid-response while someone's reading the blog.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Add swap, even on a "fast enough" instance.&lt;/strong&gt; Ampere A1 has no swap configured by default, and 12 GB with several services and an AI model loaded leaves less margin than it looks like on paper. A memory spike that would slow things down with swap available becomes an OOM-killed container without it, and Docker's OOM killer doesn't pick politely; it can take out MySQL as easily as the process that caused the spike. A modest swap file (4 GB is reasonable against 12 GB of RAM) plus a low &lt;code&gt;swappiness&lt;/code&gt; value gives the kernel somewhere to put cold pages before it starts killing containers:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Swap on a boot volume backed by network-attached block storage is slower than swap on local NVMe, so this is a safety margin for spikes, not a substitute for the RAM budget in the table above. Don't plan to run the stack out of swap day to day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tune MySQL down from its defaults.&lt;/strong&gt; Out of the box, MySQL 8's &lt;code&gt;innodb_buffer_pool_size&lt;/code&gt; defaults to 128 MB, which is conservative enough to be safe here, but the rest of its default configuration still assumes more headroom than a 12 GB shared host has to give. A small &lt;code&gt;my.cnf&lt;/code&gt; override keeps Ghost's database from creeping past the budget in the resource table:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[mysqld]
innodb_buffer_pool_size=256M
max_connections=50
table_open_cache=200
thread_cache_size=8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Mount this as &lt;code&gt;/etc/mysql/conf.d/low-memory.cnf&lt;/code&gt; in the &lt;code&gt;ghost-db&lt;/code&gt; service. It won't matter for a low-traffic personal blog, and it's the difference between MySQL sitting at 700 MB and MySQL slowly climbing toward whatever's left on the box during a traffic spike.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cap Ollama's concurrency instead of leaving it to load-balance itself.&lt;/strong&gt; Ollama's defaults assume it can decide how many models to keep loaded and how many requests to serve in parallel, which is a reasonable default on a dedicated GPU box and a bad one on a 2-core ARM instance sharing memory with everything else here. Setting explicit limits keeps one long generation from queuing up a second one and doubling memory use:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OLLAMA_NUM_PARALLEL=1
OLLAMA_MAX_LOADED_MODELS=1
OLLAMA_MAX_QUEUE=4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Add these as environment variables on the &lt;code&gt;ollama&lt;/code&gt; service in the Compose file. &lt;code&gt;OLLAMA_NUM_PARALLEL=1&lt;/code&gt; means the second request waits instead of doubling memory use by running alongside the first; on a personal instance where you're the only user, that queueing is invisible in practice and the memory ceiling it buys is not.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Want the general self-hosting stack playbook, beyond the free-tier version?&lt;/strong&gt; Our shared server-prep and reverse-proxy pattern applies whether you're on a free Ampere instance or a paid box. &lt;a href="https://sudosecurity.org/self-hosted-email-server-mailcow-setup-guide-2026/" rel="noopener noreferrer"&gt;Check out the Mailcow Guide&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sudosecurity.org/self-hosted-email-server-mailcow-setup-guide-2026/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fib3lkypwhsgma9wdd9sn.png" width="256" height="256"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Lessons from running this
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Check ARM64 support before you deploy, not after.&lt;/strong&gt; Most of the images above have solid ARM builds. A few popular self-hosting tools still don't, or only support ARM in a beta tag, and finding that out mid-migration is worse than checking before the first &lt;code&gt;docker compose up&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker manifest inspect ghost:5 | grep -A2 '"architecture"'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Look for &lt;code&gt;"architecture": "arm64"&lt;/code&gt; in the output alongside &lt;code&gt;"amd64"&lt;/code&gt;. If it's missing, the image is x86-only and won't run on the Ampere instance at all, or will run under slow QEMU emulation if Docker's configured to allow it, which defeats the point of a free ARM box.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Watch the reclamation window if traffic is thin.&lt;/strong&gt; A personal blog with a handful of daily visitors, a password vault only you touch, and a sync client that mostly sits idle can plausibly dip under Oracle's 20% utilization thresholds across a full week. Real, if modest, usage from an actual project protects you here better than any artificial workaround, and running an artificial load generator specifically to dodge the reclamation policy sits in a gray area against Oracle's terms of service that isn't worth the risk for a free instance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pin your image tags once the stack is stable.&lt;/strong&gt; &lt;code&gt;latest&lt;/code&gt; is fine while you're getting things running; once Ghost, Vaultwarden, and Ollama are doing real work, an unannounced upstream change landing on a routine &lt;code&gt;docker compose pull&lt;/code&gt; is a worse failure mode than a slightly stale version.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Back up the volumes that matter.&lt;/strong&gt; Ghost's content volume and MySQL data, Vaultwarden's data directory, and Syncthing's config and index. Model weights for Ollama are re-downloadable and not worth backing up; Uptime Kuma's history is nice to keep but not critical if it's lost.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Compose file, ready to adapt
&lt;/h2&gt;

&lt;p&gt;The full stack above, Caddy, Ghost, Vaultwarden, Syncthing, Ollama, and Uptime Kuma, is a lot to retype by hand. Grab the complete &lt;code&gt;docker-compose.yml&lt;/code&gt; and a matching &lt;code&gt;.env&lt;/code&gt; template below, drop in your own domain and secrets, and you're running rather than transcribing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get the Compose file and&lt;code&gt;.env&lt;/code&gt; template&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Enter your email and we'll send the exact configuration from this article, including the resource limits, ready to paste onto a fresh Ampere A1 instance.&lt;/p&gt;

&lt;p&gt;If you outgrow the 12 GB ceiling, that's a genuine milestone, not a failure of the free tier. It means the stack is doing enough real work that a small paid VPS or dedicated box starts paying for itself in time saved rather than money spent, and at that point the free tier has already done its job: it got you running for the cost of an afternoon instead of a monthly bill.&lt;/p&gt;

</description>
      <category>selfhosted</category>
      <category>cloud</category>
      <category>tutorial</category>
      <category>devops</category>
    </item>
    <item>
      <title>Your Code Doesn't Have to Leave the Building</title>
      <dc:creator>SudoSecurity</dc:creator>
      <pubDate>Fri, 13 Nov 2026 05:39:12 +0000</pubDate>
      <link>https://dev.to/sudosecurity/your-code-doesnt-have-to-leave-the-building-2kk7</link>
      <guid>https://dev.to/sudosecurity/your-code-doesnt-have-to-leave-the-building-2kk7</guid>
      <description>&lt;p&gt;Every developer I know has done the thing. Deadline pressure, a function that won't behave, and you paste it into a chat box because it's four in the afternoon and you want to go home.&lt;/p&gt;

&lt;p&gt;I've done it. You've done it. And most of us have never read the retention policy of the service we did it to.&lt;/p&gt;

&lt;p&gt;That's the actual situation. Not a hypothetical about corporate espionage — just a quiet, cumulative transfer of proprietary code out of the building, one frustrated paste at a time, into systems whose data-handling terms change by press release. You will find out what happened to it the same way you find out about anything: later, and from someone else.&lt;/p&gt;

&lt;p&gt;The good news is that the alternative stopped being a compromise. In 2026 you can run a model on your own hardware that outscores GPT-4o on the coding benchmarks that still mean something. It costs an afternoon and about forty gigabytes of disk. Here's the whole stack, and enough of the internals that you can fix it yourself when it misbehaves.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three Layers, and You Can Replace Any of Them
&lt;/h2&gt;

&lt;p&gt;Before an install command, get the stack straight. It's three pieces and troubleshooting depends entirely on knowing which one broke.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The weights.&lt;/strong&gt; A large binary — usually GGUF format — holding billions of numerical parameters. That's the model. A 7B at 4-bit quantization is roughly 4.6GB on disk; a 70B at the same quantization is about 43GB. Those numbers aren't rules of thumb, they're arithmetic, and the section on quantization below shows how to compute them for any model you're considering. These files are inert. They don't do anything.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The runtime.&lt;/strong&gt; Software that loads those weights into memory and runs inference against them. We're using Ollama, which wraps &lt;code&gt;llama.cpp&lt;/code&gt; behind a CLI and a REST API, handles GPU allocation, and manages model storage. It listens on &lt;code&gt;localhost:11434&lt;/code&gt;. Think Docker: you pull a thing, you run it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The interface.&lt;/strong&gt; Anything that speaks HTTP to that port. &lt;code&gt;curl&lt;/code&gt;. A Python script. A VS Code extension. A web UI. The runtime does not care.&lt;/p&gt;

&lt;p&gt;Weights on disk. Runtime loads them and exposes an API. Interface talks to the API. Swap any layer without touching the others — and when something breaks, you now know which of three places to look instead of staring at the whole thing.&lt;/p&gt;

&lt;h2&gt;
  
  
  VRAM Is the Whole Question
&lt;/h2&gt;

&lt;p&gt;Everything about local inference is a memory problem. The weights have to be somewhere fast, and how fast that somewhere is determines your tokens per second.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discrete GPU:&lt;/strong&gt; VRAM, and the model needs to fit &lt;em&gt;entirely&lt;/em&gt; inside it. Spill into system RAM and you don't degrade gracefully — you fall off a cliff. How steep that cliff is comes out of the arithmetic below, and it is much worse than most guides admit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Apple Silicon:&lt;/strong&gt; unified memory. CPU and GPU share the same pool at hardware level, so all your system RAM is effectively VRAM. This is why a MacBook with 36GB competes with a desktop running a 3090, and why the Apple path scales past where consumer GPUs stop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CPU only:&lt;/strong&gt; system RAM. Works for 3B–7B models at conversational speed. Anything bigger gets painful — single-digit tokens per second, which is fine for a question you'll wait on and useless for autocomplete.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Hardware&lt;/th&gt;
&lt;th&gt;Memory&lt;/th&gt;
&lt;th&gt;Comfortable models&lt;/th&gt;
&lt;th&gt;Rough speed&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;6–8GB VRAM&lt;/td&gt;
&lt;td&gt;6–8GB&lt;/td&gt;
&lt;td&gt;7B at Q4&lt;/td&gt;
&lt;td&gt;20–40 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;12–16GB VRAM&lt;/td&gt;
&lt;td&gt;12–16GB&lt;/td&gt;
&lt;td&gt;14B at Q4, 7B at Q8&lt;/td&gt;
&lt;td&gt;30–60 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;24GB VRAM (3090/4090)&lt;/td&gt;
&lt;td&gt;24GB&lt;/td&gt;
&lt;td&gt;32B at Q4, 14B at Q8&lt;/td&gt;
&lt;td&gt;40–80 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Apple M-series, 36GB&lt;/td&gt;
&lt;td&gt;36GB unified&lt;/td&gt;
&lt;td&gt;32B comfortably&lt;/td&gt;
&lt;td&gt;25–45 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Apple M-series, 64–96GB&lt;/td&gt;
&lt;td&gt;64–96GB unified&lt;/td&gt;
&lt;td&gt;70B at Q4&lt;/td&gt;
&lt;td&gt;35–55 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;CPU only, 32GB RAM&lt;/td&gt;
&lt;td&gt;system RAM&lt;/td&gt;
&lt;td&gt;7B at Q4, slowly&lt;/td&gt;
&lt;td&gt;5–15 tok/s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Where Those Speeds Come From
&lt;/h3&gt;

&lt;p&gt;Most guides hand you a table of tokens per second with no explanation, which makes it impossible to reason about hardware they didn't list. So here's the model.&lt;/p&gt;

&lt;p&gt;For a dense transformer, generating one token requires reading &lt;strong&gt;every weight&lt;/strong&gt; from memory once. That makes generation memory-bandwidth-bound, not compute-bound, and gives you a hard ceiling:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tokens/sec ceiling = memory bandwidth ÷ model size in memory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Published bandwidth figures, run against common model sizes at Q4:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                                    7B       14B       32B       70B
RTX 4090 (GDDR6X, 1008 GB/s)       214       112        50        25
RTX 3090 (GDDR6X,  936 GB/s)       199       104        47        23
M3 Ultra (unified, 800 GB/s)       170        89        40        20
M3 Max 40-core   (400 GB/s)         85        44        20        10
M3 Max 14-core   (300 GB/s)         64        33        15         8
DDR5-6000 dual channel (96 GB/s)    20        11         5         2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Those are ceilings, not measurements — real throughput lands somewhere under them depending on the runtime, the quantization, batch handling and how much of the bandwidth you actually get. But the ratios hold, and the ratios are what you're buying.&lt;/p&gt;

&lt;p&gt;Check it against published benchmarks and the model behaves: a 70B at Q4 on an M3 Ultra has a ceiling of 20 tok/s, and reported real-world figures for 70–72B on high-end Apple Silicon sit around 9–14. Roughly half the ceiling, consistently, which is what you'd expect.&lt;/p&gt;

&lt;p&gt;Now the important number. GDDR6X on a 4090 moves about 1,008 GB/s. Dual-channel DDR5 moves about 96. That's a &lt;strong&gt;10.5× gap&lt;/strong&gt; , which means any layer that doesn't fit in VRAM runs about ten times slower than the same layer would have in VRAM.&lt;/p&gt;

&lt;p&gt;That is the cliff. Not a 30% penalty, not "somewhat slower" — an order of magnitude on every offloaded layer, which is why published tests of a 70B at Q4 on a single 24GB card report throughput collapsing into single digits. The model didn't get worse. Most of it is being read across a bus a tenth as fast.&lt;/p&gt;

&lt;p&gt;It also explains the two things about this table that look strange at first glance. Apple Silicon competes with discrete GPUs despite lower peak bandwidth &lt;strong&gt;because the model fits&lt;/strong&gt; — 400 GB/s that holds all the weights beats 1,008 GB/s that holds two thirds of them. And CPU-only inference isn't slow because CPUs are weak at math; it's slow because dual-channel DDR5 is a tenth the pipe.&lt;/p&gt;

&lt;p&gt;Capacity first. Bandwidth second. In that order, always.&lt;/p&gt;

&lt;p&gt;The practical floor for real work is an 8GB GPU running a 7B coding model. Twenty to forty tokens per second is faster than you read. That's enough.&lt;/p&gt;

&lt;p&gt;If you're buying: a used RTX 3090 is still the value pick in 2026. Same 24GB as a 4090, runs the same models, costs meaningfully less. The 4090 is faster; it is not more capable. Above that, Apple Silicon with 64GB+ is the only consumer route to 70B-class models without stacking cards.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;On AMD&lt;/strong&gt; , be careful, because this is where the previous version of this guide contradicted itself. AMD acceleration on Linux via ROCm is genuinely competitive — a 7900 XTX trades blows with a 3090. On Windows, Ollama does not officially support AMD GPU acceleration; you're on WSL2 or CPU. And &lt;strong&gt;check Ollama's current ROCm version requirement before you install anything&lt;/strong&gt; , because it has moved more than once and a guide written six months ago will send you to the wrong package.&lt;/p&gt;

&lt;p&gt;Storage: 100GB of NVMe if you want a few models around. Capacity is the obvious reason; load time is the one people underestimate. Model load is a straight sequential read, so it's pure bandwidth:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                            4.7GB (7B)  20GB (32B)  43GB (70B)
NVMe Gen4 (~7 GB/s)               1 s         3 s         6 s
NVMe Gen3 (~3.5 GB/s)             1 s         6 s        12 s
SATA SSD (~550 MB/s)              9 s        37 s        79 s
7200rpm HDD (~150 MB/s)          32 s      2.3 min     4.8 min
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A 32B off NVMe is a three-second pause. Off a spinning disk it's &lt;strong&gt;two and a half minutes&lt;/strong&gt; , every cold start, every time the keep-alive window expires. That's not a minor inconvenience, it's the difference between a tool you reach for and one you avoid because you don't want to wait.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you're enjoying what you've read so far, we recommend &lt;a href="https://sudosecurity.org/stable-diffusion-local-setup-guide-2026/" rel="noopener noreferrer"&gt;Stable Diffusion Local Setup: RTX 3090 vs Apple Silicon&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Installing the Runtime
&lt;/h2&gt;

&lt;p&gt;Linux:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -fsSL https://ollama.com/install.sh | sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That sets up a systemd service. Verify it's alive:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ollama --version
systemctl status ollama
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;macOS and Windows get installers from &lt;code&gt;ollama.com/download&lt;/code&gt;. One macOS gotcha worth stating because it wastes an evening: if you install the app, &lt;strong&gt;do not also run&lt;code&gt;ollama serve&lt;/code&gt;&lt;/strong&gt;. The app already runs the server. Both means a port conflict on 11434 and a confusing error.&lt;/p&gt;

&lt;p&gt;Then the only verification that actually matters:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ollama run llama3.1:8b "say hello"
ollama ps
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;ollama ps&lt;/code&gt; shows you where the model actually landed:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;NAME              ID              SIZE    PROCESSOR    UNTIL
llama3.1:8b       365c0bd3109b    6.7 GB  100% GPU     4 minutes from now
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;100% GPU&lt;/code&gt; is the goal. If you see &lt;code&gt;100% CPU&lt;/code&gt; on a machine with a supported card, stop and fix the driver before going further. The difference is roughly 35 tokens per second against 5, and every other decision you make downstream is meaningless until this line is right.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which Models, and Why the Benchmark Everyone Quotes Is Useless
&lt;/h2&gt;

&lt;p&gt;For coding, the Qwen2.5-Coder family is the answer on consumer hardware, and it isn't close.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ollama pull qwen2.5-coder:7b     # fits 8GB VRAM
ollama pull qwen2.5-coder:14b    # 16GB, noticeably better on hard tasks
ollama pull qwen2.5-coder:32b    # 24GB, where local stops apologising
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, the numbers — and this is the part the previous version of this guide got wrong, so let's do it properly.&lt;/p&gt;

&lt;p&gt;You will see HumanEval scores quoted everywhere. &lt;strong&gt;Ignore them.&lt;/strong&gt; The benchmark is saturated: nearly every current model scores above 90%, which means it has stopped distinguishing between them. Qwen2.5-Coder-7B scores in the high 80s. The 32B is around 92%. GPT-4o is about 90%. Those numbers are all the same number wearing different hats, and a two-point gap on a saturated benchmark tells you nothing about whether the thing can refactor your service layer.&lt;/p&gt;

&lt;p&gt;The benchmarks that still separate models are the ones that haven't been trained into oblivion:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LiveCodeBench&lt;/strong&gt; — Qwen2.5-Coder-32B scores &lt;strong&gt;37.2%&lt;/strong&gt; , against GPT-4o's &lt;strong&gt;29.2%&lt;/strong&gt;. The 7B lands around 28.6%.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Aider&lt;/strong&gt; (code repair, not generation) — the 32B scores &lt;strong&gt;73.7&lt;/strong&gt; , roughly comparable to GPT-4o.
Read that first line again. A 32B model you can run on a single 24GB card outscores GPT-4o on LiveCodeBench. Not "approaches." Outscores. That's the actual state of local coding models in 2026, and it's a much stronger claim than anything HumanEval will tell you.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For general chat and research, Llama 3.1 8B is the workhorse and 3.3 70B is the ceiling if you have the memory. For step-by-step debugging, DeepSeek R1 thinks out loud before answering — you'll see &lt;code&gt;&amp;lt;think&amp;gt;&lt;/code&gt; tags in the output, which is the point, not a bug. On minimal hardware, Phi-4 Mini and Gemma 3 1B are surprisingly capable for their size.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quantization: Fewer Bits, More Parameters
&lt;/h2&gt;

&lt;p&gt;Weights are trained at FP16 or FP32. Quantization drops that precision to save memory, and the key insight is that inference doesn't need training precision. Going FP16 → 4-bit cuts the footprint roughly 75% for modest quality loss.&lt;/p&gt;

&lt;p&gt;The naming is misleading, though, and it's worth knowing why. A "4-bit" k-quant is not 4 bits per weight — the K-quant formats store block scales and minimums alongside the weights, so the real figure is higher. Effective bits per weight, which is what actually determines file size:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Format&lt;/th&gt;
&lt;th&gt;Bits/weight&lt;/th&gt;
&lt;th&gt;vs F16&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;F16&lt;/td&gt;
&lt;td&gt;16.00&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Q8_0&lt;/td&gt;
&lt;td&gt;8.50&lt;/td&gt;
&lt;td&gt;47%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Q6_K&lt;/td&gt;
&lt;td&gt;6.56&lt;/td&gt;
&lt;td&gt;41%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Q5_K_M&lt;/td&gt;
&lt;td&gt;5.67&lt;/td&gt;
&lt;td&gt;35%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Q4_K_M&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;4.83&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;30%&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Q3_K_M&lt;/td&gt;
&lt;td&gt;3.91&lt;/td&gt;
&lt;td&gt;24%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Which makes model size a one-line calculation:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;size in GB = parameters (billions) x bits_per_weight / 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Check it against reality — computed against what Ollama actually ships:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  qwen2.5-coder:7b     computed  4.6 GB | published  4.7 GB | delta 2.1%
  llama3.1:8b          computed  4.8 GB | published  4.9 GB | delta 1.1%
  qwen2.5-coder:32b    computed 19.8 GB | published 20.0 GB | delta 1.0%
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Within two percent across the range. So you can size any model on any hardware before downloading a single byte, including ones nobody has written a guide about.&lt;/p&gt;

&lt;p&gt;Note also that &lt;code&gt;Q4_K_M&lt;/code&gt; lands at &lt;strong&gt;70% smaller&lt;/strong&gt; than F16, not the 75% everyone repeats — that gap is the k-quant metadata, and on a 32B model it's a couple of gigabytes you need to budget for.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;_K_M&lt;/code&gt; suffix means mixed quantization: more precision preserved in the layers that affect output quality most. It beats naive Q4 at nearly identical size, which is why Ollama pulls it by default.&lt;/p&gt;

&lt;p&gt;Now the rule worth internalising: &lt;strong&gt;more parameters at lower precision beats fewer parameters at higher precision.&lt;/strong&gt; Run the arithmetic on a 12GB budget:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  7B  @ Q8_0   =  8.1 GB
  14B @ Q4_K_M =  8.9 GB   &amp;lt;- more params, same budget
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Nearly identical footprint, twice the parameters. Take the bigger model and the cheaper bits.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Context Setting That Silently Eats Your Data
&lt;/h2&gt;

&lt;p&gt;This is the single most expensive thing to not know, and it's why "the model forgot what we were talking about" is the most common complaint about local setups.&lt;/p&gt;

&lt;p&gt;When your conversation exceeds the context window, Ollama does not error. It &lt;strong&gt;silently drops the oldest tokens&lt;/strong&gt; and keeps going. The model answers confidently using half your input. Nothing in the output tells you this happened.&lt;/p&gt;

&lt;p&gt;Worse, the default is smaller than people assume and it is no longer one number. Ollama now picks a default based on detected VRAM: roughly &lt;strong&gt;4K under 24GiB, 32K for 24–48GiB, and 256K above that&lt;/strong&gt;. So the same command on your workstation and your laptop gives you two very different context windows, and only one of them will quietly truncate the file you pasted.&lt;/p&gt;

&lt;p&gt;There are three ways to change it, and they are not equivalent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In the REPL, temporarily&lt;/strong&gt; — gone when the model unloads:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/set parameter num_ctx 32768
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;For the whole server&lt;/strong&gt; , via environment variable:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OLLAMA_CONTEXT_LENGTH=64000 ollama serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Permanently, per model&lt;/strong&gt; , with a Modelfile — the one that actually survives a reboot:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM qwen2.5-coder:14b
PARAMETER num_ctx 32768



ollama create qwen-coder-32k -f Modelfile
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That rebuild doesn't re-download anything; it stacks a config layer on the existing weights. Note the underscore in &lt;code&gt;num_ctx&lt;/code&gt; — a hyphenated &lt;code&gt;num-ctx&lt;/code&gt; inside a Modelfile is silently invalid, which is a wonderful thing to discover three hours later.&lt;/p&gt;

&lt;p&gt;And via the API, per request:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl http://localhost:11434/api/generate -d '{
  "model": "qwen2.5-coder:14b",
  "prompt": "...",
  "options": { "num_ctx": 32768 }
}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Context costs VRAM. A 32K window uses substantially more than 4K on the same model — budget for it, or you'll push layers out of GPU and wonder why everything got slow. For agent and coding-tool workloads, Ollama's own guidance is to set at least 64,000 tokens explicitly rather than trusting the auto-default.&lt;/p&gt;

&lt;p&gt;If you take one thing from this article, take this: &lt;strong&gt;check your context length before you blame the model.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What Context Actually Costs in VRAM
&lt;/h2&gt;

&lt;p&gt;"Larger context uses more VRAM" is where every guide stops. That's not good enough to plan with, because the number is computable and it's bigger than people expect.&lt;/p&gt;

&lt;p&gt;The KV cache holds the key and value tensors for every token in the window, on every layer. Its size is:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bytes = 2 (K and V) x layers x kv_heads x head_dim x context x bytes_per_element
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Qwen2.5-7B's published architecture: &lt;strong&gt;28 layers, hidden size 3584, 28 query heads, 4 key-value heads.&lt;/strong&gt; Head dimension is 3584 ÷ 28 = 128. At fp16, two bytes per element:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;2 x 28 x 4 x 128 x 2 = 57,344 bytes per token
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Fifty-seven kilobytes of VRAM per token of context. Which scales exactly how you'd fear:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   context     KV cache    total w/ 4.7GB Q4 weights
     4,096       0.22 GB                     4.92 GB
     8,192       0.44 GB                     5.14 GB
    16,384       0.88 GB                     5.58 GB
    32,768       1.75 GB                     6.45 GB
    65,536       3.50 GB                     8.20 GB
   131,072       7.00 GB                    11.70 GB
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Read the right column against your card. A 7B at Q4 with a 4K window fits an 8GB GPU with room to spare. Push it to 64K and you need more than 8GB — the weights didn't change, the cache ate the difference. &lt;strong&gt;That's the actual mechanism behind "I raised my context and everything got slow."&lt;/strong&gt; You didn't hit a software limit. You pushed layers out of VRAM and into system RAM, and now you're paying the spill penalty on every token.&lt;/p&gt;

&lt;p&gt;There's a second thing hiding in that formula worth understanding, because it's why any of this is affordable at all. Qwen uses grouped-query attention: 28 query heads share just &lt;strong&gt;4&lt;/strong&gt; key-value heads. The KV cache scales with &lt;code&gt;kv_heads&lt;/code&gt;, not &lt;code&gt;q_heads&lt;/code&gt;. Run the same arithmetic with 28 KV heads, as older architectures had:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;without GQA (28 KV heads) at 32k: 12.25 GB   &amp;lt;- 7x larger
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Seven times the cache. A 32K context on a 7B model would need over twelve gigabytes for the cache alone, before the weights. GQA is the single architectural change that made long context viable on consumer hardware, and it's invisible in every spec sheet you'll read.&lt;/p&gt;

&lt;p&gt;Plug your own model's numbers into that formula before you set &lt;code&gt;num_ctx&lt;/code&gt;. &lt;code&gt;ollama show &amp;lt;model&amp;gt;&lt;/code&gt; gives you the architecture. Then you're sizing a context window on arithmetic instead of raising it until something breaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Halving the Cache Without Touching the Context
&lt;/h2&gt;

&lt;p&gt;The KV cache doesn't have to be fp16. Ollama can quantize it, and this is the single biggest lever for running long context on a small card.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OLLAMA_KV_CACHE_TYPE=q8_0 ollama serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Per Ollama's own FAQ, &lt;code&gt;q8_0&lt;/code&gt; uses about half the memory of f16 "with a very small loss in precision, this usually has no noticeable impact on the model's quality." &lt;code&gt;q4_0&lt;/code&gt; gets you to roughly a quarter with a real, measurable trade-off. Applied to the numbers above:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  context       f16      q8_0      q4_0
    8,192    0.44 GB   0.22 GB   0.11 GB
   32,768    1.75 GB   0.88 GB   0.44 GB
   65,536    3.50 GB   1.75 GB   0.88 GB
  131,072    7.00 GB   3.50 GB   1.75 GB
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now make it concrete. An 8GB card holding a 7B at Q4 has roughly 3GB left after weights and overhead:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    65,536 @ f16   =  3.50 GB  spills
    65,536 @ q8_0  =  1.75 GB  FITS
   131,072 @ f16   =  7.00 GB  spills
   131,072 @ q4_0  =  1.75 GB  FITS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A 64K context that does not fit at f16 fits comfortably at &lt;code&gt;q8_0&lt;/code&gt;, on the same hardware, for a precision loss the Ollama docs describe as unnoticeable. That's a genuinely free upgrade and almost nobody sets it.&lt;/p&gt;

&lt;p&gt;Three caveats, and the third one will cost you an afternoon if you don't know it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;It requires flash attention to be active.&lt;/strong&gt; Older guides tell you to set &lt;code&gt;OLLAMA_FLASH_ATTENTION=1&lt;/code&gt;; on current builds it's on by default for supported hardware and the variable now acts as a three-state override.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flash attention does not shrink the cache.&lt;/strong&gt; This gets repeated wrong constantly. It computes attention in blocks that fit in GPU SRAM, which makes the operation faster and lowers peak transient memory. The K and V vectors are still stored in full. It is a speed optimisation that happens to be a prerequisite for the memory optimisation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;On unsupported architectures it silently falls back to f16.&lt;/strong&gt; Not a warning. Not an error. Ollama's own issue tracker documents developers setting &lt;code&gt;q8_0&lt;/code&gt;, calculating their VRAM budget against half-size cache, and then hitting unexpected OOMs because the server quietly kept using f16. So verify rather than assume:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;grep "KV self size" ~/.ollama/logs/server.log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That line reports the actual cache size and type the runtime allocated. If it says f16 after you asked for q8_0, your architecture isn't on the allowlist and every capacity calculation you just did is wrong.&lt;/p&gt;

&lt;p&gt;One more detail worth knowing if you push to q4_0: the K cache is measurably more sensitive to quantization than the V cache. Ollama exposes a single global setting, but the underlying llama.cpp allows them to be set separately, and the quality-per-byte sweet spot in community testing has been q8_0 keys with q4_0 values. If you're running llama.cpp directly, that's the configuration to try before accepting q4_0 across the board.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Still with us? We think you'll like &lt;a href="https://sudosecurity.org/complete-self-hosted-ai-stack-2026/" rel="noopener noreferrer"&gt;The Complete Self-Hosted AI Stack for 2026&lt;/a&gt; as your next read.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  A Web Interface, in One Command
&lt;/h2&gt;

&lt;p&gt;Terminal is fine for smoke tests. For real use you want history, file uploads, and model switching. Open WebUI, entirely local:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -d \
  -p 3000:8080 \
  --add-host=host.docker.internal:host-gateway \
  -v open-webui:/app/backend/data \
  --name open-webui \
  --restart always \
  ghcr.io/open-webui/open-webui:main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The flag that people drop and then can't debug is &lt;code&gt;--add-host=host.docker.internal:host-gateway&lt;/code&gt;. Without it the container has no route to Ollama on the host, and the failure looks like Open WebUI simply not finding any models.&lt;/p&gt;

&lt;p&gt;It lands at &lt;code&gt;http://localhost:3000&lt;/code&gt; and asks you to create an admin account — stored locally, no registration, nothing leaves. If auto-detection fails, point it at &lt;code&gt;http://host.docker.internal:11434&lt;/code&gt; on macOS and Windows, or &lt;code&gt;http://172.17.0.1:11434&lt;/code&gt; on Linux.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wiring It Into VS Code
&lt;/h2&gt;

&lt;p&gt;This is where local stops being a privacy argument and starts being a tool you actually use. The Continue extension gives you inline completion and chat against your local runtime.&lt;/p&gt;

&lt;p&gt;Configure two models, not one, and configure them differently:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Autocomplete&lt;/strong&gt; fires on every keystroke. Put the 7B there. Latency is the entire product.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Chat&lt;/strong&gt; is something you deliberately invoked and are already waiting on. Put the 14B or 32B there.
Continue has changed its configuration schema more than once — check its current docs for the exact file and format rather than copying a config from any guide, including this one. What matters conceptually is that each entry points at &lt;code&gt;provider: ollama&lt;/code&gt; and &lt;code&gt;apiBase: http://localhost:11434&lt;/code&gt;, and that the autocomplete model is the small fast one.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The feature that justifies the whole exercise is codebase context. Asking &lt;em&gt;"find everywhere we don't handle the error from the database call"&lt;/em&gt; means indexing your repository. With a cloud model that means shipping your repository to somebody else — which is exactly the thing most employers prohibit and most developers do anyway. Locally it's just a disk read.&lt;/p&gt;

&lt;p&gt;A review loop that works:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Make changes on a branch.&lt;/li&gt;
&lt;li&gt;In chat: &lt;code&gt;@diff Summarize these changes and flag any bugs or security issues.&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Read the response as a first-pass reviewer, not a verdict.
Nothing leaves. The diff stays on the machine that made it.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  When It Breaks
&lt;/h2&gt;

&lt;p&gt;Five failures cover almost everything, and each one has a diagnostic that takes ten seconds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;ollama ps&lt;/code&gt; says 100% CPU on a machine with a GPU.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The runtime never found your card. Check the driver first, then the logs:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvidia-smi                       # NVIDIA: driver present and version?
rocm-smi                         # AMD on Linux: ROCm present?
journalctl -u ollama -n 50       # what did detection actually say?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The Ollama log records the detection attempt and the specific reason it failed. Usual causes: driver older than Ollama's minimum, missing ROCm runtime on AMD Linux, or a card that isn't on the supported list. Fix this before anything else — you are otherwise tuning a system running seven times slower than it should.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output is garbled, repetitive, or incoherent.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Check &lt;code&gt;ollama ps&lt;/code&gt; for a split load. If the processor column says something like &lt;code&gt;60% GPU / 40% CPU&lt;/code&gt;, the model didn't fit and part of it is in system RAM. Pull a smaller quantization, pull a smaller model, or reduce context so the whole thing fits. Coherent-but-slow is a spill; incoherent usually means something worse — try re-pulling the model in case the download corrupted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The model "forgot" the beginning of the conversation.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Context truncation, silently. Covered above — check your &lt;code&gt;num_ctx&lt;/code&gt; against what you actually fed it. This is the single most common complaint about local setups and it is almost never a model quality problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open WebUI can't see any models.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Test the runtime directly first, from the host:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl http://localhost:11434/api/tags
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;JSON list of models means Ollama is fine and the problem is Docker networking — confirm &lt;code&gt;--add-host=host.docker.internal:host-gateway&lt;/code&gt; is present, and on Linux try pointing the UI at &lt;code&gt;http://172.17.0.1:11434&lt;/code&gt;. A connection error means Ollama itself isn't running and the UI is innocent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Everything is slow despite a working GPU.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Something else is holding VRAM. Watch it live:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvidia-smi --loop=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Another model still loaded, a browser doing GPU compositing, a game you forgot about. Unload what you're not using:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ollama stop &amp;lt;model&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Models stay resident for a keep-alive window after use, which is a feature until you're running two and wondering why the second one crawls.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to Check Before You Ask Anyone for Help
&lt;/h2&gt;

&lt;p&gt;In order, because this sequence answers most questions before they get asked:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ollama ps                                    # is it on the GPU at all?
ollama show &amp;lt;model&amp;gt;                          # architecture, context, quantization
grep "KV self size" ~/.ollama/logs/server.log  # what cache did it actually allocate?
journalctl -u ollama -n 50                   # what did it say when it loaded?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Four commands. Between them they tell you where the model is running, how big its window is, what the cache cost, and what the runtime thought about all of it. Almost every "why is my local LLM bad" question is answered somewhere in that output.&lt;/p&gt;

&lt;h2&gt;
  
  
  When the Cloud Is Still the Right Call
&lt;/h2&gt;

&lt;p&gt;I'd rather be useful than partisan, so: local is not always the answer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Frontier reasoning still favours the cloud.&lt;/strong&gt; Decompiling obfuscated binaries, architecting a distributed system, chasing a subtle race condition across a large codebase — the biggest hosted models remain better at the genuinely hard end. Local has closed most of the gap on everyday work and not all of it on the hard stuff.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wanting a 70B without the memory for one is not a plan.&lt;/strong&gt; Running a 70B at Q4 on an 8GB card means spilling to system RAM and living at single-digit tokens per second. You will hate it and stop using it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Serving customers is a different problem.&lt;/strong&gt; A model on your workstation is a tool. A model serving production traffic is inference infrastructure — batching, queueing, autoscaling, GPU scheduling. Don't confuse the two because the &lt;code&gt;ollama run&lt;/code&gt; command looked easy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And you'll lag the frontier by days to weeks.&lt;/strong&gt; New models reach hosted APIs before they reach the Ollama library.&lt;/p&gt;

&lt;p&gt;For everything else — daily coding, review, research, documentation, the endless small questions you'd never open a ticket for — local wins on cost, on latency, on being there at 3AM when the hosted API is having an incident.&lt;/p&gt;

&lt;p&gt;And on the one thing you can't buy back. Every other cost here is recoverable: hardware depreciates, models get better, a bad quantization choice is a re-pull. Code that left the building did that permanently, and no amount of hardware brings it home.&lt;/p&gt;

&lt;p&gt;That's the argument. Everything above is just the implementation.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>selfhosted</category>
      <category>llm</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
