惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
J
Java Code Geeks
博客园_首页
Scott Helme
Scott Helme
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
Security Latest
Security Latest
V
Visual Studio Blog
Cloudbric
Cloudbric
Jina AI
Jina AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
S
SegmentFault 最新的问题
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
W
WeLiveSecurity
K
Kaspersky official blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
量子位
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 三生石上(FineUI控件)
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The Architecture Decisions That Actually Mattered: Building a Production-Ready Multi-Service Backend
U C H E N N A · 2026-06-01 · via DEV Community

What most system design articles skip is the part where you explain why the boring choice was the right one


I built a platform that runs social media giveaway events, a gift card marketplace, and telecom gift vending — all in one system, all sharing the same PostgreSQL database and Redis instance, all running in production on infrastructure that costs €27 a month.

This article is not about the product. It is about the seven architectural decisions I made while building the backend, why I made them, and what the actual capacity ceiling looks like before anything needs to change.

The full architecture document (20 sections, every design decision documented) is linked at the end. This is the version you can read in ten minutes.


1. Three services, not ten — and not one

The backend is a NestJS monorepo with three independently deployable applications:

  • Giveaway API (port 5000) — events, participants, host wallet, auth, admin
  • Giftcard API (port 5002) — cards, merchants, escrow, redemptions, merchant wallet
  • Job Processor (port 5001 / 5003) — background work only, no HTTP surface

This is not a microservice architecture. It is a modular monolith with a deployment boundary.

The question most engineers get wrong is treating "microservices" as the goal rather than as a tool. I had two bounded domains with genuinely different data ownership and access patterns. Splitting them gave me independent deployability and the ability to scale each service's connection pool separately. Splitting further — into separate auth services, notification services, payment services — would have added coordination overhead with no operational gain at this scale.

The monorepo means all three apps share one build pipeline, one migration runner, one set of gRPC contract types, and one test suite. Changes to shared infrastructure (JWT guards, Redis config, payment client) deploy everywhere in one merge. You get the organisational clarity of separate services without the dependency management nightmare of separate repositories.


2. gRPC between services, not HTTP

The Giveaway API and Giftcard API call each other constantly. The Giveaway side calls Giftcard to allocate prize escrows, issue gift card instances, and refund expired holds. The Giftcard side calls Giveaway to validate winner PINs, credit wallet refunds, and log payment audit records.

The standard answer is REST. I used gRPC instead, for three concrete reasons.

Typed contracts enforced at compile time. The request and response shapes live in .proto files and are compiled into TypeScript interfaces that both the caller and handler must satisfy. If you rename a field in the Giftcard service's response, the Giveaway service fails to compile. With REST JSON, that failure happens in production.

Bidirectional calls without auth overhead. Both services call each other, over an internal Docker network. gRPC over TCP with no auth headers, no CORS, no URL routing. Just a typed method call that the runtime handles.

Every gRPC call is persisted through Bull, not just retried in memory. This is the part most architectures get wrong. A custom Proxy (createQueuedGrpcService) intercepts every gRPC method call before it reaches the wire. Instead of calling the stub directly, it enqueues a GRPC_CALL Bull job — serialising the service name, method name, and request payload into Redis. The Job Processor picks up the job and executes the actual gRPC stub:

API calls giftcardService.allocateCards(payload)
    → Proxy intercepts the call
    → Enqueues GRPC_CALL job to Bull (persisted to Redis)
    → Awaits job.finished() with a deadline timeout
    → Job Processor picks up job, executes real gRPC stub
    → Result returned to the waiting caller

The caller still receives the response synchronously — from the outside it behaves like a direct call. But the transport goes through Redis, which means the call survives an API process restart, and Bull's retry policy handles failures at the execution layer. If the Job Processor is temporarily down, the call sits durably in Redis until it comes back.

On top of this, a circuit breaker sits at the proxy level — before any job is enqueued. After five consecutive failures, the circuit opens and the proxy immediately rejects calls without touching Redis or the network. This prevents a struggling downstream service from filling the Bull queue with jobs that will all fail.


3. Redis is doing four different jobs simultaneously

This is the part of the architecture that surprises most engineers when they see it.

The same single Redis instance handles all of the following, concurrently:

Bull queue backend. Six job queues — email, social verification, notifications, analytics, event processing, WebSocket — all backed by Redis lists and sorted sets. AOF persistence is enabled, so queued jobs survive a Redis restart.

Socket.IO pub/sub adapter. The WebSocket gateway runs in a separate process from the API. When the Job Processor needs to emit giveaway.winner to an event room, it publishes to a Redis channel. Every gateway instance subscribed to that channel propagates the event to connected clients. This is what makes horizontal scaling of the WebSocket layer possible without any code changes — add more gateways, they all share rooms via Redis.

TTL-based application cache. A CacheService wraps Redis with a getOrSet(key, factory, ttl) pattern. Merchant wallet balances, bank lists, admin analytics aggregates, service fee rates — all cached with appropriate TTLs and invalidated on write. If Redis is unavailable, the cache degrades gracefully to always calling the database rather than throwing.

Atomic concurrency control. The real-time winner selection algorithm uses a Lua script executed atomically inside Redis. During a live event, up to hundreds of participants may submit prize attempts simultaneously. The script increments a budget counter only if it is below the current time-slot threshold — preventing over-awarding regardless of concurrent load, without any application-level locking.

local v = redis.call('GET', k)
if not v then v = 0 else v = tonumber(v) end
if v < lim then
  v = v + 1
  redis.call('SET', k, v)
  if exp and exp > 0 then redis.call('EXPIRE', k, exp) end
  return v
else
  return -1
end

One Redis instance. Four distinct, production-critical responsibilities. No Kafka, no separate cache cluster, no dedicated counter service.


4. The escrow state machine is where financial correctness lives

Gift card prizes work as follows: a host allocates cards to a prize pool, funds are held in escrow, winners claim their card, and the merchant receives the net settlement when the card is physically redeemed at a branch.

RESERVED → SETTLED   (redeemed at branch POS)
    │
    └─→ RELEASED  (event cancelled / prize unassigned / expiry)

Every state transition is irreversible. Every financial operation carries an idempotency key. The settlement calculation strips out the payment provider's deposit fee before applying the platform service rate — because the provider already took that fee at topup time, and charging a service fee on money the platform never held would be a systematic double-charge on merchants.

The most important design decision here is the ordering of operations at settlement. Two payment transfers must happen: one to the merchant's payout account, one to the platform's fee account. If the database were committed first and then a transfer failed, a compensation transaction would be needed. Instead, both transfers run before any database write. A failure on either leg leaves the database untouched, and the client retries safely — both transfer references are idempotent, so a retry after a partial success is clean.

Finalization, where prize escrows are first created via cross-service gRPC calls, uses an inline saga compensation pattern. If the wallet deduction fails after one or more escrows have been reserved, the catch block immediately refunds each escrow before re-throwing the error. Promise.allSettled ensures a failed refund on one prize does not block the others.


5. The job processor runs in two separate modes

The job processor binary starts in one of three modes controlled by JOB_MODE:

  • JOB_MODE=worker — email sending, event draws, social API verification, analytics
  • JOB_MODE=gateway — Socket.IO WebSocket server only
  • JOB_MODE=all — both, for development

These scale on completely different axes. Workers scale when the job queue backlog grows. Gateways scale when the number of concurrent WebSocket connections grows. A worker crash means queued jobs drain slower — the data is safe in Redis. A gateway crash means connected clients briefly disconnect and reconnect via Socket.IO's built-in reconnection. These are independent failure modes with no coupling.

The API processes never touch Socket.IO directly. When the Giveaway API needs to broadcast a winner announcement to everyone in an event room, it enqueues a job. The gateway dequeues it and emits. This keeps the HTTP event loop free from the overhead of maintaining persistent connections.

Scaling either process is one command:

docker compose up --scale worker-prod=4 -d
docker compose up --scale gateway-prod=3 -d

Bull distributes jobs across all worker instances automatically. The Redis adapter keeps Socket.IO rooms synchronised across all gateway instances automatically. No Kubernetes required.


6. Observability: infrastructure errors go to Sentry, not to users

The observability design makes a deliberate distinction between two categories of errors.

User-facing errors (validation failures, not-found, unauthorised) are returned as structured HTTP responses. The user sees a clear message. The application handles them with ErrorInterceptor and ErrorFilter.

Infrastructure errors (Nomba transfer failed, gRPC circuit open, Bull job exhausted retries, Redis connection dropped) are captured to Sentry in production and never propagate to the user as HTTP 500s with internal stack traces. These are engineering signals, not user messages.

Every infrastructure boundary has an explicit Sentry capture:

@OnQueueFailed()
onFailed(job: Job, error: Error) {
  const isLastAttempt = job.attemptsMade >= (job.opts.attempts ?? 1);
  if (!isLastAttempt) return;

  Sentry.withScope((scope) => {
    scope.setTag('queue', QueueName.EVENT_PROCESSING);
    scope.setExtra('correlationId', job.data?.correlationId);
    Sentry.captureException(error);
  });
}

Sentry capture is disabled in development and staging — development generates constant infrastructure noise (Redis not yet connected, gRPC services starting up) that would drown the production error stream.

Every HTTP request carries an x-correlation-id header that is propagated into every Bull job enqueued during that request. When a social verification job fails ninety seconds after the original HTTP request, the Sentry event includes the correlation ID — making it possible to trace the failure to the originating user action without a distributed tracing platform.


7. The honest capacity ceiling

With one VPS (8 vCPU, 16 GB RAM), one PostgreSQL VPS, and default TypeORM connection pools, this is what the system handles:

Scenario Capacity
Concurrent browsing / dashboard reads 300–500 req/s
Simultaneous event registrations ~100–200
Concurrent auth operations ~50–100
Concurrent WebSocket connections 5,000–10,000
Total comfortable active users 1,000–3,000
Total registered users (10–20% active) 15,000–30,000

The first wall is the TypeORM connection pool, which defaults to 10 connections per app. Three apps × 10 = 30 connections total. Increasing this to 25 per app costs nothing and roughly triples concurrent write capacity:

extra: {
  max: 25,
  min: 2,
  idleTimeoutMillis: 30000,
}

The WebSocket ceiling is per gateway instance. Each additional gateway instance added via --scale increases this linearly, because the Redis adapter keeps rooms synchronised.


8. The scaling roadmap

The architecture is designed so that each scaling action is independent and requires no code changes:

Stage 1 (now): Single VPS, tune connection pools, run 1 gateway + 1 worker. Handles 15,000–30,000 registered users.

Stage 2: Add more workers (--scale worker-prod=3). Scales queue throughput. No infrastructure change.

Stage 3: Move Redis to a dedicated VPS when adding a second app VPS. All instances point at the same Redis URL. Bull queues and Socket.IO rooms synchronise automatically.

Stage 4: Add a second app VPS. Traefik load-balances across both. No code changes.

Stage 5 (Kubernetes): Only justified when managing 3+ VPS nodes manually becomes operationally expensive. The current Docker Compose setup maps nearly 1:1 to Kubernetes Deployments when that time comes — stateless containers, externalised config, health checks already defined.


The full architecture document covers every decision documented here in depth, plus: the database schema separation design, the full gRPC contract structure, the presigned URL file upload pattern, the drift-corrected countdown timer implementation, the complete financial flow for every money movement in the system, and the detailed scaling migration procedures.

Read the full architecture document → https://blog.ucheofor.xyz/post/537tg0


Built with NestJS 11, TypeScript, PostgreSQL 15, Redis 7, gRPC, Bull, Socket.IO, Traefik, and Docker on Hetzner Cloud.