Engineering Problem Playbooks

Web & API Authentication, Session Cookies & Token Hardening

Avoid session hijacking, XSS token theft, CSRF, and OAuth misconfigurations when implementing authentication with Better Auth, Clerk, or custom OAuth2/OIDC flows.

  • Storing bearer session tokens in browser localStorage: Any injected script or compromised npm widget can read localStorage directly; prefer HttpOnly, Secure, SameSite=Lax cookies for browser sessions.
  • Long-lived stateless JWTs without revocation: Issuing 30-day stateless JWTs prevents instant session revocation on password reset, compromised account, or role downgrade.
  • Skipping OAuth2 state and PKCE verification: Omitting cryptographic state validation enables login CSRF, while omitting PKCE exposes authorization codes on mobile and SPA redirects.
  • Weak password hashing or missing rate limits: Using unsalted SHA-256 or unthrottled login endpoints permits rapid credential stuffing; use Argon2id or scrypt plus per-IP and per-account throttling.

Multi-Tenant Isolation with PostgreSQL Row-Level Security (RLS)

Prevent cross-tenant data leaks in shared-database B2B SaaS by pairing least-privilege PostgreSQL roles, transaction-scoped SET LOCAL tenant context, and RLS policies.

  • Connecting as table owner or BYPASSRLS role: PostgreSQL table owners bypass RLS by default unless FORCE ROW LEVEL SECURITY is enabled, and superusers or roles with BYPASSRLS always bypass RLS.
  • Using SET instead of SET LOCAL with connection poolers: In PgBouncer or Supavisor transaction pooling, session-level SET leaks across pooled requests; always bind tenant context inside a transaction via SET LOCAL.
  • Missing WITH CHECK clause on writes: A USING policy alone guards reads and updates of existing rows, while INSERT and new UPDATE values require explicit WITH CHECK predicates.
  • Unindexed tenant_id leading columns: RLS appends tenant predicates to every query; without composite indexes leading with tenant_id, tables degrade to full sequential scans.

Production Hybrid RAG Retrieval, Chunking & Prompt-Injection Defense

Fix low recall and hallucinated answers in RAG pipelines by combining lexical BM25 search with dense vectors via Reciprocal Rank Fusion (RRF), metadata filtering, and eval harnesses.

  • Relying on dense embeddings alone: Semantic embeddings compress exact identifiers (like ERR_TLS_CERT_ALTNAME_INVALID or invoice IDs); pairing BM25 full-text search with dense vectors lifts recall sharply.
  • Applying tenant or ACL filters after vector top-K search: Post-filtering top-10 vector matches leaks unauthorized documents or returns zero results; enforce hard metadata/tenant pre-filters inside the index query.
  • Blind fixed-character chunking without document context: Splitting every 500 characters detaches paragraphs from their document title, section heading, and version metadata.
  • Shipping RAG without an offline retrieval eval set: Changing chunk size, embedding model, or reranker without measuring Recall@K and citation faithfulness leads to silent quality regressions.

Connection Pooling & Prepared Statements in Serverless PostgreSQL

Prevent max_connections exhaustion, prepared-statement errors, and cold-start latency spikes when connecting Vercel, Cloudflare Workers, or AWS Lambda functions to PostgreSQL.

  • Opening direct TCP pools inside stateless functions: Each concurrent serverless isolate spawns its own connection pool; 200 warm isolates times 10 pooled connections instantly exhausts a standard Postgres instance.
  • Leaving protocol-level prepared statements enabled on incompatible poolers: Transaction-mode poolers multiplex clients onto different backend connections between transactions, breaking unnamed or session-scoped prepared statements unless explicitly supported or disabled.
  • Running DDL migrations through a transaction pooler: Schema migrations often rely on advisory locks and session-scoped settings that fail or deadlock under transaction pooling; always use a direct session URL for migrations.

Idempotent Stripe Billing & Webhook Processing

Build crash-safe, duplicate-proof Stripe webhook handlers using raw-body HMAC verification, database event deduplication, and decoupled durable state updates.

  • Parsing JSON before verifying Stripe-Signature: HMAC verification requires the exact raw UTF-8 request bytes; running express.json() or req.json() first breaks constructEvent().
  • Trusting webhook delivery to happen once and in order: Stripe explicitly guarantees at-least-once delivery and does not guarantee strict event ordering; handlers must be idempotent and state-reconciling.
  • Doing slow external work before returning HTTP 200: Sending emails, calling third-party APIs, or running heavy reports inline causes webhook timeouts, triggering retry storms.
  • Trusting redirect query strings on Checkout success pages: Never activate paid access from a client-side redirect URL alone; treat signed webhooks (or server-side Stripe API retrieval) as the source of truth.

Zero-Downtime Expand-and-Contract Database Migrations

Roll out SQL schema changes on live production databases without locking traffic or breaking in-flight rolling application deployments.

  • Running CREATE INDEX without CONCURRENTLY: Standard CREATE INDEX acquires a SHARE lock that blocks all INSERT, UPDATE, and DELETE statements on the table for the entire index build.
  • Renaming or dropping columns in the same deploy as application code: During rolling deployments, old (N-1) and new (N) application code run simultaneously against the same database schema.
  • Omitting lock_timeout on DDL statements: Even a fast metadata-only ALTER TABLE queues behind an open transaction and blocks every new query behind it unless lock_timeout fails fast and retries.
  • Backfilling millions of rows in one giant transaction: Single-transaction backfills create massive WAL spikes, dead tuple bloat, replication lag, and long-held row locks.