Engineering Case Study

Linkforge: Multi-Tenant Link-in-Bio & Analytics Engine

An in-depth breakdown of designing tenant-isolated data architectures, fail-fast configuration schemas, atomic slug mutations, and asynchronous clickstream analytics pipelines.

Role

Full-Stack / Backend Engineer

Status

In Progress

Timeline

March 2026 – Present

Architecture

pnpm workspaces

This is just for a demonstration purposes. *

Table of Contents10 Sections
01//OVERVIEW

Building the Primitives First

When building modern SaaS products, developers frequently reach for batteries-included auth frameworks, hosted databases, and black-box cloud analytics before understanding the fundamental primitives.

Linkforge was built with a deliberate rule: understand the primitives before allowing abstractions to hide them. Before integrating higher-level orchestration, the application was architected with raw JWT validation, manual session cookies, raw PostgreSQL schemas, and custom Express middleware.

02//THE PROBLEM & CONSTRAINTS

What Makes Link-in-Bio Technically Non-Trivial?

On the surface, a link-in-bio app seems like a basic CRUD list of URLs. However, supporting multi-tenant isolation with real-time telemetry presents complex backend engineering requirements:

  • Multi-Tenant Boundary Enforcement: Preventing accidental data leakage between user accounts without bloating every query with boilerplate.
  • Concurrent Slug Collisions: Preventing race conditions when users modify their vanity URL handles at the exact same moment.
  • High-Volume Telemetry Logging: Capturing clickstream events, geolocation, and referrer headers without slowing down visitor HTTP 302 redirects.
  • Fail-Fast Startup Integrity: Guaranteeing the API cannot boot in an invalid state due to missing environment configurations.
03//ENGINEERING GOALS

Design Requirements

Zero Tenant Leakage

100% of read/write queries must be scoped to verified tenant identifiers.

Sub-Millisecond Redirects

Critical path link forwarding decoupled from analytics event persistence.

Fail-Fast Configuration

Zod validation at boot time prevents runtime config crashes in production.

Atomic Slug Safety

Interactive database transactions eliminate vanity handle race conditions.

04//SYSTEM ARCHITECTURE

Monorepo & Multi-Tier Topology

Linkforge is organized as a pnpm workspace monorepo isolating client presentation from API and worker services:

linkforge-monorepo topologypnpm-workspace
apps/web(Next.js App Router)
Public Bio Pages · Authenticated Analytics Dashboard
↓ HTTP / REST / Secure Cookies
apps/api(Express & Node.js)
Tenant Middleware · Zod Schema · Auth Pipeline
↓ Data Persistence & Message Queue
PostgreSQL

Users · Links · Tenant Workspaces · Daily Aggregates

Redis & Workers

Async Event Queue · Rate Limiter · Fast Session Revocation

05//CORE ENGINEERING CHALLENGES
04 Deep Dives

Difficult Technical Problems & Solutions

CHALLENGE 01

Multi-Tenant Data Isolation & Query Partitioning

The Challenge & Risk

In a SaaS platform where multiple users configure links, custom domains, and view private analytics, a single un-scoped SQL query could inadvertently leak tenant data.

Risk: Cross-tenant data contamination, unauthorized analytics inspection, and privacy violations.

The Approach

Engineered an authentication middleware that extracts verified tenant and user identity from signed HttpOnly session cookies. Every database repository function strictly requires `tenantId` / `userId` in its WHERE clause, preventing cross-tenant access at the repository contract level.

The Result

Guaranteed logical data isolation across all tenant workspaces with comprehensive unit tests verifying that tenant A cannot access or mutate tenant B resources.

apps/api/src/middleware/tenant-auth.ts
export const requireTenantAuth = (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
) => {
  const token = req.cookies["auth_session"]
  if (!token) {
    return res.status(401).json({ error: "Unauthorized: Missing session" })
  }

  try {
    const payload = jwt.verify(token, config.JWT_SECRET) as SessionPayload
    req.user = { id: payload.userId, email: payload.email }
    req.tenantId = payload.tenantId
    next()
  } catch (err) {
    return res.status(401).json({ error: "Invalid or expired session" })
  }
}

Extracts verified session credentials from HttpOnly cookies and attaches immutable tenant context to the Express request pipeline.

CHALLENGE 02

Handling Username & Vanity Slug Race Conditions

The Challenge & Risk

When a user attempts to update their profile username or link vanity slug (`/u/:username`), two concurrent requests submitting the same new slug could pass an initial `findUnique()` check before either writes, resulting in collision.

Risk: Broken link routing, duplicate vanity handles, and routing ambiguity.

The Approach

Utilized PostgreSQL strict unique constraints backed by Prisma interactive transactions (`$transaction`). The mutation performs an atomic reservation lock: if a concurrent process claims the slug within the transaction window, the database rejects the secondary commit with a deterministic conflict error.

The Result

100% deterministic uniqueness verification during concurrent slug renames with clean client error propagation.

apps/api/src/services/user-service.ts
export async function updateUsername(userId: string, newSlug: string) {
  const normalized = newSlug.toLowerCase().trim()

  return prisma.$transaction(async (tx) => {
    const existing = await tx.user.findUnique({
      where: { username: normalized },
      select: { id: true }
    })

    if (existing && existing.id !== userId) {
      throw new ConflictError("Username is already claimed by another user.")
    }

    return tx.user.update({
      where: { id: userId },
      data: { username: normalized }
    })
  })
}

Guarantees atomic validation and persistence inside a single database transaction, preventing time-of-check to time-of-use (TOCTOU) race conditions.

CHALLENGE 03

Fail-Fast Environment Diagnostics at Startup

The Challenge & Risk

In early iterations, reading `process.env.DATABASE_URL` directly meant the server booted successfully and only crashed when the first database call executed minutes later.

Risk: Silent deployment of broken environments, masked CI/CD errors, and production runtime crashes.

The Approach

Implemented a Zod schema validation module at the application entrypoint. Before initializing Express or connecting to PostgreSQL, the configuration module parses `process.env`. If any variable is missing, mistyped, or fails regex checks, the process exits immediately with a structured diagnostic error.

The Result

Zero silent startup errors. Deployments fail immediately if environment contracts are violated.

apps/api/src/config/env.ts
import { z } from "zod"

const envSchema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
  PORT: z.coerce.number().default(4000),
  DATABASE_URL: z.string().url(),
  JWT_SECRET: z.string().min(32, "JWT secret must be at least 32 characters"),
  REDIS_URL: z.string().url().optional(),
})

const parsed = envSchema.safeParse(process.env)

if (!parsed.success) {
  console.error("❌ Invalid environment configuration:", parsed.error.format())
  process.exit(1)
}

export const env = parsed.data

Enforces compile-time and boot-time schema validation across all required environment variables.

CHALLENGE 04

Decoupled Asynchronous Analytics Ingestion

The Challenge & Risk

Logging visitor telemetry (IP geolocation, device header, referrer, timestamp) synchronously inside the redirect handler added 80-150ms of latency to each link click.

Risk: Slow redirect times, database connection pool exhaustion during traffic spikes, and degraded user experience.

The Approach

Decoupled redirect execution from analytics recording. The redirect handler issues an immediate HTTP 302/307 redirect while pushing the event payload to an asynchronous ingestion queue. A background worker processes and aggregates click metrics into hourly and daily summary tables.

The Result

Sub-millisecond redirect processing overhead, with reliable eventual consistency for analytics reporting.

06//CODE PRIMITIVES & SECURITY

Security & Authentication Primitives

Authentication state is persisted exclusively via HttpOnly, Secure, SameSite cookies with signed JWT payloads containing user and tenant identifiers.

This prevents cross-site scripting (XSS) attacks from accessing session tokens in `localStorage`, while CSRF protection is enforced on all mutating REST endpoints via custom header validation.

07//DATA FLOW PIPELINES

Asynchronous Click Ingestion Pipeline

The redirect and telemetry lifecycle is split across fast and slow paths:

1
Visitor clicks vanity link

Request hits `/r/:slug` endpoint on Express API.

2
Instant HTTP 302/307 Redirect dispatched

Destination URL retrieved from cache/database; visitor redirected immediately (<5ms).

3
Telemetry pushed to background worker

Referrer, user agent, IP hash, and timestamp dispatched to Redis queue without blocking client.

4
Aggregation & Dashboard Updates

Worker processes batches into hourly/daily summary tables in PostgreSQL for instant dashboard queries.

08//TECHNOLOGY STACK

Architecture Stack

Frontend

Next.js 16App Router & Server Components
React 19Concurrent UI rendering
TypeScript 5Strict end-to-end typing
Tailwind CSS v4Design tokens & styling
MotionAccessible UI animations

Backend & API

Node.js & ExpressDecoupled API service
TypeScriptType-safe controllers & middleware
ZodRuntime schema validation & config
bcrypt & JWTPassword hashing & HttpOnly tokens
Better AuthMulti-session OAuth orchestration

Database & Infrastructure

PostgreSQLRelational data with foreign keys
Prisma ORMType-safe migrations & transactions
RedisFast event buffering & rate limits
DockerContainerized reproducible services
pnpm WorkspacesClient-server monorepo isolation
09//RESULTS & OUTCOMES

Verified Outcomes

Reliable Multi-Tenant Partitioning

Strict query scoping and session-bound tenant IDs eliminate the possibility of cross-account data leakage.

Deterministic Slug Rename Safety

Interactive transactions and unique constraint reservations handle concurrent vanity URL changes without conflict.

100% Fail-Fast Startup Validation

Schema-enforced boot diagnostics guarantee zero silent mid-request crashes from unconfigured environment variables.

10//LESSONS LEARNED

Engineering Reflections

1. Earn your abstractions: Implementing manual JWT cookies, bcrypt hashing, and raw SQL queries before introducing Better Auth and Prisma gave me deep clarity into session lifetimes, cookie flags, and database index costs.

2. Configuration errors should be startup errors: Validating the environment schema before launching HTTP listeners saves hours of production debugging and makes CI/CD deployments foolproof.

3. Protect the critical path: Separating high-frequency redirects from telemetry persistence is vital for maintaining snappy user experiences at scale.