[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M733B83NJ4EQR0WMCM7V47DV":3,"skill-same:01M733B83NJ4EQR0WMCM7V47DV":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M733B83NJ4EQR0WMCM7V47DV","backend-architecture",null,"Design backends that survive redeploys, server reboots, and modest scaling. Covers stateless application servers, state placement (object storage, managed databases, Redis), immutable deploy artifacts, health checks, graceful shutdown, database migrations that don't lock the world, and the twelve-factor baseline. Invoke when designing a new backend, when uploads disappear after a redeploy, or when productionizing a vibe-coded prototype.","Horonomos-laps\u002FYana-AI","Horonomos-laps","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F355299122?v=4","01M76B3QPXE88ET2SQPDPVATZT"," Horonomos-laps","01M72ZQRJPCYPSSWT4D00VJR2A",13,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fgw360--backend-architecture\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: backend-architecture\ndescription: Design backends that survive redeploys, server reboots, and modest scaling. Covers stateless application servers, state placement (object storage, managed databases, Redis), immutable deploy artifacts, health checks, graceful shutdown, database migrations that don't lock the world, and the twelve-factor baseline. Invoke when designing a new backend, when uploads disappear after a redeploy, or when productionizing a vibe-coded prototype.\n---\n\n# Backend Architecture — the Solutions Architect Baseline\n\nThe most common mistake in vibe-coded backends is treating the application server as if it were a desktop computer: state lives where the code lives, the disk is permanent, restarts are exceptional, one instance runs forever. None of that survives contact with production.\n\nThis skill is the **architectural baseline** that makes a backend production-ready. It is not security-specific — but a backend that loses data, drops jobs, or rolls back to a half-state during deploys is also a backend whose incident-response surface looks much larger than it should. Pairs with the hardening skills, but operates at a different layer.\n\n## When to invoke\n\n- \"User uploads disappeared after we redeployed\"\n- \"The site went down during deploy and we lost the in-flight orders\"\n- \"I need to scale to a second server but nothing works when there are two\"\n- \"We're moving from prototype to production\"\n- \"We're handing off the codebase to a team that has to run it\"\n- Designing a new backend from scratch and you want the decisions correct on day one\n- Reviewing an inherited backend before scaling user count or revenue\n\n## The single most important rule\n\n> **App servers are cattle. State lives elsewhere.**\n\nAny data that must survive a deploy, reboot, container restart, or instance replacement is **state**. State does not belong on the app server's local disk, in its memory, or anywhere bound to the instance's lifetime. It belongs in a system designed for durability.\n\nThis rule, followed consistently, eliminates 80% of \"where did my data go?\" incidents.\n\n## The state-placement decision matrix\n\nFor every piece of data your app handles, decide where it lives **before** writing the code:\n\n| Data type | Right place | Wrong place |\n|---|---|---|\n| User-uploaded files (images, PDFs, docs) | Object storage (S3, R2, B2, Spaces) behind a CDN | App server's `uploads\u002F` directory |\n| Generated thumbnails \u002F derivatives | Object storage, or regenerated on-demand from originals | App server's filesystem |\n| Database rows (orders, users, posts) | Managed Postgres \u002F MySQL, or a dedicated DB VM with backups | SQLite next to the app code |\n| Session data | Redis, managed cache, or DB-backed sessions | In-process memory (`Map`, `WeakMap`) |\n| Cache (computed data, hot reads) | Redis \u002F Memcached \u002F Cloudflare KV | Local memory if and only if loss-tolerant |\n| Background-job state | Persistent queue (BullMQ + Redis, AWS SQS, GCP Pub\u002FSub, NATS JetStream) | `setTimeout` \u002F `setInterval` in the web process |\n| Logs | Centralized log destination (Loki, hosted, syslog forwarding) | App server's `\u002Fvar\u002Flog` only |\n| Secrets | Env vars from a secret manager, or runtime injection | `.env` checked into the image \u002F repo |\n| Search index | Managed search (Algolia, Meilisearch, Elasticsearch, Postgres GIN) | Recomputed from DB on every request |\n| Email-sending | Transactional ESP (Postmark, Mailgun, SES, Resend) | Direct SMTP from the app server in production |\n\nEvery \"Wrong place\" row in the table is a real outage waiting to happen. Walk this list against your current codebase — anything misplaced is a refactor candidate.\n\n## The \"images disappear on redeploy\" trap — concretely\n\nThis one bites everyone once. Anatomy:\n\n1. App is built as a Docker image. Image is immutable.\n2. App writes uploaded images to `.\u002Fuploads\u002F` (relative to working directory inside the container).\n3. Deploy: new image is pulled, old container stopped, new container started.\n4. The new container has a fresh filesystem from the image. The `uploads\u002F` directory exists but is empty.\n5. All previously-uploaded user images now return 404.\n\nThe same trap occurs without Docker: PaaS platforms (Heroku, Railway, Fly, Render) typically run on ephemeral filesystems. The \"disk\" is a feature of the container, not the platform.\n\n### Fix — use object storage\n\n```ts\n\u002F\u002F Bad — writes to local disk that disappears on redeploy\nimport fs from 'node:fs\u002Fpromises';\nasync function saveUpload(file: Buffer, key: string) {\n  await fs.writeFile(`.\u002Fuploads\u002F${key}`, file);\n  return `\u002Fuploads\u002F${key}`;   \u002F\u002F served by app, lost on deploy\n}\n\n\u002F\u002F Good — write to S3-compatible storage; URL is permanent\nimport { S3Client, PutObjectCommand } from '@aws-sdk\u002Fclient-s3';\n\nconst s3 = new S3Client({\n  region: 'auto',\n  endpoint: process.env.S3_ENDPOINT,        \u002F\u002F R2: https:\u002F\u002F\u003Cacct>.r2.cloudflarestorage.com\n  credentials: {\n    accessKeyId: process.env.S3_ACCESS_KEY_ID!,\n    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,\n  },\n});\n\nasync function saveUpload(file: Buffer, key: string) {\n  await s3.send(new PutObjectCommand({\n    Bucket: process.env.S3_BUCKET,\n    Key: key,\n    Body: file,\n    ContentType: detectMime(file),\n  }));\n  return `${process.env.CDN_BASE_URL}\u002F${key}`;  \u002F\u002F served by CDN, survives redeploy\n}\n```\n\n**Recommended stack** (cheap and fast for small\u002Fmedium projects):\n\n- **Cloudflare R2** for storage — zero egress fees, S3-compatible API\n- **Cloudflare custom domain** in front of R2 for the public URLs\n- **Pre-signed URLs** for uploads if you want the browser to upload directly to R2 (bypasses your app server for big files)\n\nAlternatives: AWS S3 + CloudFront, Backblaze B2, DigitalOcean Spaces, MinIO if you must self-host.\n\nSee [`cloudflare-hardening`](..\u002Fcloudflare-hardening\u002FSKILL.md) for the R2-specific security configuration.\n\n## Sessions — the second redeploy-killer\n\nIf your sessions live in-process (Express `express-session` with default `MemoryStore`, Next.js naive session-in-Map), every deploy logs out every user. Same problem if you scale to two instances — half of requests land on the instance that never saw the login.\n\n```ts\n\u002F\u002F Bad — default Express in-memory session store\nimport session from 'express-session';\napp.use(session({ secret: process.env.SESSION_SECRET! }));  \u002F\u002F MemoryStore by default!\n\n\u002F\u002F Good — Redis-backed session\nimport { createClient } from 'redis';\nimport RedisStore from 'connect-redis';\n\nconst redis = createClient({ url: process.env.REDIS_URL });\nawait redis.connect();\n\napp.use(session({\n  store: new RedisStore({ client: redis }),\n  secret: process.env.SESSION_SECRET!,\n  cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 7 * 24 * 60 * 60 * 1000 },\n}));\n```\n\nStateless alternatives:\n\n- **Signed cookies** (the session payload itself is in the cookie, signed by the server). Works for small sessions; the cookie grows with the data.\n- **JWT** with short TTL + refresh tokens. See [`auth-hardening`](..\u002Fauth-hardening\u002FSKILL.md) for the tradeoffs.\n\n## Background jobs — `setTimeout` is not a queue\n\n```ts\n\u002F\u002F Bad — process is killed on deploy, job never runs\napp.post('\u002Fapi\u002Fsign-up', async (req, res) => {\n  await db.users.create(req.body);\n  setTimeout(() => sendWelcomeEmail(req.body.email), 60_000);   \u002F\u002F ☠️\n  res.json({ ok: true });\n});\n\n\u002F\u002F Good — persistent queue, retries, observability\nimport { Queue, Worker } from 'bullmq';\n\nconst emailQueue = new Queue('emails', { connection: { url: process.env.REDIS_URL }});\n\napp.post('\u002Fapi\u002Fsign-up', async (req, res) => {\n  await db.users.create(req.body);\n  await emailQueue.add('welcome', { email: req.body.email }, {\n    attempts: 5,\n    backoff: { type: 'exponential', delay: 1000 },\n    removeOnComplete: 1000,\n  });\n  res.json({ ok: true });\n});\n\n\u002F\u002F Worker — separate process, can be on the same or different host\nnew Worker('emails', async (job) => {\n  await sendWelcomeEmail(job.data.email);\n}, { connection: { url: process.env.REDIS_URL }});\n```\n\nWhat you get:\n- Retries with backoff\n- Dead-letter queue for poison messages\n- Persistence — restarting the worker does not lose jobs\n- Observable — BullMQ has an admin UI\n\nFor cron-style \"every hour\" jobs, the right place is **also** the queue (BullMQ has `repeat`, or use a dedicated cron worker), or a managed scheduler (AWS EventBridge, Cloudflare Workers Cron). Not a `setInterval` in the web process.\n\n## Deploys — immutable artifacts, health checks, graceful shutdown\n\nThree patterns that together make deploys boring:\n\n### Immutable artifacts\n\nA deploy is \"ship this exact image \u002F artifact to production.\" Not \"pull, install, configure.\" The same artifact that ran in staging runs in prod. If something breaks in prod, rolling back means pointing at the previous artifact — no re-install, no risk of a different state.\n\n- Docker image with explicit tag (`myapp:1.2.3` or SHA-digest), not `:latest`\n- Or built bundle (zip \u002F tarball) checked into a versioned artifact store\n- Build once, deploy that exact thing to every environment\n\n### Health checks\n\nTwo endpoints, two purposes:\n\n```ts\n\u002F\u002F Liveness — is the process alive? Cheap, no dependencies.\napp.get('\u002Fhealthz', (req, res) => res.json({ ok: true }));\n\n\u002F\u002F Readiness — is the process actually ready to serve traffic?\napp.get('\u002Freadyz', async (req, res) => {\n  try {\n    await Promise.all([\n      db.$queryRaw`SELECT 1`,\n      redis.ping(),\n    ]);\n    res.json({ ok: true });\n  } catch (err) {\n    res.status(503).json({ ok: false, err: String(err) });\n  }\n});\n```\n\nThe orchestrator (Docker, Kubernetes, your reverse proxy) routes traffic only when `\u002Freadyz` returns 200. Without this, new containers get traffic before they have warmed connections to the DB and produce 500s for the first 30 seconds of every deploy.\n\n### Graceful shutdown\n\nWhen the orchestrator sends `SIGTERM`, stop accepting new requests, finish in-flight ones, close connections, then exit. Most frameworks ship this; some make you wire it.\n\n```ts\nconst server = app.listen(port);\n\nconst shutdown = async (signal: string) => {\n  console.log(`${signal} — draining`);\n  server.close(async () => {\n    await redis.quit();\n    await db.$disconnect();\n    process.exit(0);\n  });\n  \u002F\u002F Hard cap — if drain takes too long, force exit\n  setTimeout(() => process.exit(1), 30_000).unref();\n};\n\nprocess.on('SIGTERM', () => shutdown('SIGTERM'));\nprocess.on('SIGINT', () => shutdown('SIGINT'));\n```\n\nCombined: zero-downtime rolling deploys become trivial.\n\n## Database operations — migrations and connections\n\n### Migrations\n\n- **Forward-compatible by default**: never break the old code. New code can run against old schema, old code can run against new schema, until both sides have rolled out.\n- **Expand-then-contract**: add a new column \u002F table first, deploy code that writes to both, backfill, then remove the old. No \"rename column\" in a single migration in production.\n- **Lock-free for large tables**: in Postgres, prefer `ADD COLUMN ... DEFAULT NULL` (instant) over `ADD COLUMN ... DEFAULT 'x' NOT NULL` (rewrites the table). Use `CREATE INDEX CONCURRENTLY` for indexes on large tables.\n- **Run migrations as a separate step**, not at app boot. Two app instances racing to run the same migration at startup is its own incident class.\n\n### Connection pooling\n\nApp processes open too many connections to Postgres by default. Postgres struggles past ~100 active connections. Use a pooler:\n\n- **PgBouncer** — battle-tested, transaction-mode for most apps\n- **Supabase, Neon, RDS Proxy** — managed pooler in front of managed Postgres\n- **Prisma Accelerate** \u002F **Drizzle's pool** — ORM-level pooling\n\nSet per-instance pool size = `(maxConnections \u002F numInstances)` − headroom. For 4 instances and a 100-connection budget, that's ~20 connections per instance with 20 spare.\n\nSee [`postgres-hardening`](..\u002Fpostgres-hardening\u002FSKILL.md) for the security side.\n\n## Idempotency — survive retries\n\nEvery state-changing operation should produce the same effect whether it runs once or ten times. This is what makes retries, queues, and replays safe.\n\n- **Webhook handlers** dedupe on the provider's event ID. See [`stripe-webhook-security`](..\u002Fstripe-webhook-security\u002FSKILL.md).\n- **Order creation** dedupes on a client-generated idempotency key (`X-Idempotency-Key` header), not on auto-incremented IDs.\n- **Email sends** dedupe on `(template, recipient, trigger-id)`.\n- **File uploads** dedupe on content hash (compute SHA-256 of the file, use as the object key).\n\nA retry storm should be boring, not catastrophic.\n\n## Observability — three pillars, minimum viable\n\nFor a small backend, \"observability\" is not a buzzword — it is three concrete things:\n\n1. **Centralized logs** — see [`log-strategy`](..\u002Flog-strategy\u002FSKILL.md). Cloud logging, Loki, hosted. Not \"ssh in to read \u002Fvar\u002Flog\".\n2. **Per-request tracing** — generate a `request_id` at the edge (Cloudflare adds one for free), thread it through every log line and every downstream service call. When something breaks, you can reconstruct the full path.\n3. **Error reporting** — Sentry \u002F Rollbar \u002F Highlight \u002F GlitchTip. Each unhandled exception lands with stack trace, breadcrumbs, user context. Without this you only see errors users actively complain about.\n\nMetrics (Prometheus \u002F Grafana \u002F Datadog) are great when traffic grows; not day-one critical.\n\n## The cost-aware tier — when to add complexity\n\nMost vibe-coded projects do not need Kubernetes, microservices, multi-region, or a service mesh. The cost of premature complexity is real: more failure modes, more \"why is this not working\" hours, more bills.\n\nReasonable trajectory:\n\n| Stage | Architecture |\n|---|---|\n| 0–1k users | Single VPS, app + Postgres + Redis colocated, daily off-host backups, Cloudflare in front |\n| 1k–10k users | Same, plus object storage for files, separate worker process, managed Postgres or DB on a dedicated VM |\n| 10k–100k users | Multiple app instances behind a load balancer, managed Postgres with read replica, queue is its own service, CDN is essential |\n| 100k+ users | Dedicated DB nodes, autoscaling app tier, regional split if latency demands, real SRE practices |\n\nSkip stages only if you have a specific reason. \"We might need Kubernetes someday\" is not a reason for today.\n\n## Twelve-Factor — the canonical reference\n\nMost of this skill is a practical application of [The Twelve-Factor App](https:\u002F\u002F12factor.net), an excellent guide written in 2011 that has aged remarkably well. The twelve factors:\n\n1. **Codebase** — one codebase tracked in revision control, many deploys\n2. **Dependencies** — explicitly declared and isolated (lockfiles)\n3. **Config** — stored in the environment, not the code\n4. **Backing services** — treated as attached resources (DB, cache, queue are configurable)\n5. **Build, release, run** — strictly separate stages\n6. **Processes** — execute the app as one or more stateless processes\n7. **Port binding** — export services via port binding (no external web server required at the app layer)\n8. **Concurrency** — scale out via the process model\n9. **Disposability** — fast startup and graceful shutdown\n10. **Dev\u002Fprod parity** — keep dev, staging, and production as similar as possible\n11. **Logs** — treat logs as event streams\n12. **Admin processes** — run admin\u002Fmanagement tasks as one-off processes\n\nRead it once. Then read it again every six months. Most \"production incidents\" in small-team backends are violations of one of these twelve.\n\n## Quick architecture review checklist\n\nBefore declaring a backend production-ready, walk through:\n\n- [ ] App processes are stateless — restarting an instance loses nothing\n- [ ] User uploads go to object storage (S3 \u002F R2 \u002F equivalent), not local disk\n- [ ] Sessions are in Redis \u002F DB \u002F signed cookies, not in-process memory\n- [ ] Background jobs run via a persistent queue, not `setTimeout` \u002F `setInterval`\n- [ ] Cron jobs run via a real scheduler, not the web process\n- [ ] Cache is explicit (Redis \u002F KV \u002F CDN), not implicit in-memory hashmaps\n- [ ] Database has off-host backups, restore-tested at least once\n- [ ] Database migrations are forward-compatible; never \"rename + drop\" in one step\n- [ ] Connection pooling is in place (PgBouncer or equivalent)\n- [ ] App has `\u002Fhealthz` (liveness) and `\u002Freadyz` (readiness) endpoints\n- [ ] App handles `SIGTERM` gracefully — drains connections, finishes in-flight work\n- [ ] Deploys produce immutable artifacts (image tag or SHA digest), no in-place mutation\n- [ ] Rollback is a single command pointing at a previous artifact\n- [ ] Logs ship to a central destination, with `request_id` threading\n- [ ] Unhandled errors land in Sentry \u002F equivalent\n- [ ] All state-changing operations are idempotent\n- [ ] Configuration is in env vars; no environment-specific values baked into the image\n- [ ] `.env` is not in the image, not in the repo\n\nIf anything is \"no\", you have an outage waiting. Fix before scaling, not after.\n\n## What this skill will not do\n\n- Tell you to use Kubernetes \u002F microservices \u002F multi-region for a project that does not need them\n- Endorse writing application data to the app server's local disk in production\n- Help build a backend whose deploys lose user data because \"we'll fix it later\"\n- Replace experience — architecture is judgment. This skill gives you the patterns; the calls are still yours\n","# Backend Architecture — the Solutions Architect Baseline\n\nThe most common mistake in vibe-coded backends is treating the application server as if it were a desktop computer: state lives where the code lives, the disk is permanent, restarts are exceptional, one instance runs forever. None of that survives contact with production.\n\nThis skill is the **architectural baseline** that makes a backend production-ready. It is not security-specific — but a backend that loses data, drops jobs, or rolls back to a half-state during deploys is also a backend whose incident-response surface looks much larger than it should. Pairs with the hardening skills, but operates at a different layer.\n\n## When to invoke\n\n- \"User uploads disappeared after we redeployed\"\n- \"The site went down during deploy and we lost the in-flight orders\"\n- \"I need to scale to a second server but nothing works when there are two\"\n- \"We're moving from prototype to production\"\n- \"We're handing off the codebase to a team that has to run it\"\n- Designing a new backend from scratch and you want the decisions correct on day one\n- Reviewing an inherited backend before scaling user count or revenue\n\n## The single most important rule\n\n> **App servers are cattle. State lives elsewhere.**\n\nAny data that must survive a deploy, reboot, container restart, or instance replacement is **state**. State does not belong on the app server's local disk, in its memory, or anywhere bound to the instance's lifetime. It belongs in a system designed for durability.\n\nThis rule, followed consistently, eliminates 80% of \"where did my data go?\" incidents.\n\n## The state-placement decision matrix\n\nFor every piece of data your app handles, decide where it lives **before** writing the code:\n\n| Data type | Right place | Wrong place |\n|---|---|---|\n| User-uploaded files (images, PDFs, docs) | Object storage (S3, R2, B2, Spaces) behind a CDN | App server's `uploads\u002F` directory |\n| Generated thumbnails \u002F derivatives | Object storage, or regenerated on-demand from originals | App server's filesystem |\n| Database rows (orders, users, posts) | Managed Postgres \u002F MySQL, or a dedicated DB VM with backups | SQLite next to the app code |\n| Session data | Redis, managed cache, or DB-backed sessions | In-process memory (`Map`, `WeakMap`) |\n| Cache (computed data, hot reads) | Redis \u002F Memcached \u002F Cloudflare KV | Local memory if and only if loss-tolerant |\n| Background-job state | Persistent queue (BullMQ + Redis, AWS SQS, GCP Pub\u002FSub, NATS JetStream) | `setTimeout` \u002F `setInterval` in the web process |\n| Logs | Centralized log destination (Loki, hosted, syslog forwarding) | App server's `\u002Fvar\u002Flog` only |\n| Secrets | Env vars from a secret manager, or runtime injection | `.env` checked into the image \u002F repo |\n| Search index | Managed search (Algolia, Meilisearch, Elasticsearch, Postgres GIN) | Recomputed from DB on every request |\n| Email-sending | Transactional ESP (Postmark, Mailgun, SES, Resend) | Direct SMTP from the app server in production |\n\nEvery \"Wrong place\" row in the table is a real outage waiting to happen. Walk this list against your current codebase — anything misplaced is a refactor candidate.\n\n## The \"images disappear on redeploy\" trap — concretely\n\nThis one bites everyone once. Anatomy:\n\n1. App is built as a Docker image. Image is immutable.\n2. App writes uploaded images to `.\u002Fuploads\u002F` (relative to working directory inside the container).\n3. Deploy: new image is pulled, old container stopped, new container started.\n4. The new container has a fresh filesystem from the image. The `uploads\u002F` directory exists but is empty.\n5. All previously-uploaded user images now return 404.\n\nThe same trap occurs without Docker: PaaS platforms (Heroku, Railway, Fly, Render) typically run on ephemeral filesystems. The \"disk\" is a feature of the container, not the platform.\n\n### Fix — use object storage\n\n```ts\n\u002F\u002F Bad — writes to local disk that disappears on redeploy\nimport fs from 'node:fs\u002Fpromises';\nasync function saveUpload(file: Buffer, key: string) {\n  await fs.writeFile(`.\u002Fuploads\u002F${key}`, file);\n  return `\u002Fuploads\u002F${key}`;   \u002F\u002F served by app, lost on deploy\n}\n\n\u002F\u002F Good — write to S3-compatible storage; URL is permanent\nimport { S3Client, PutObjectCommand } from '@aws-sdk\u002Fclient-s3';\n\nconst s3 = new S3Client({\n  region: 'auto',\n  endpoint: process.env.S3_ENDPOINT,        \u002F\u002F R2: https:\u002F\u002F\u003Cacct>.r2.cloudflarestorage.com\n  credentials: {\n    accessKeyId: process.env.S3_ACCESS_KEY_ID!,\n    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,\n  },\n});\n\nasync function saveUpload(file: Buffer, key: string) {\n  await s3.send(new PutObjectCommand({\n    Bucket: process.env.S3_BUCKET,\n    Key: key,\n    Body: file,\n    ContentType: detectMime(file),\n  }));\n  return `${process.env.CDN_BASE_URL}\u002F${key}`;  \u002F\u002F served by CDN, survives redeploy\n}\n```\n\n**Recommended stack** (cheap and fast for small\u002Fmedium projects):\n\n- **Cloudflare R2** for storage — zero egress fees, S3-compatible API\n- **Cloudflare custom domain** in front of R2 for the public URLs\n- **Pre-signed URLs** for uploads if you want the browser to upload directly to R2 (bypasses your app server for big files)\n\nAlternatives: AWS S3 + CloudFront, Backblaze B2, DigitalOcean Spaces, MinIO if you must self-host.\n\nSee [`cloudflare-hardening`](..\u002Fcloudflare-hardening\u002FSKILL.md) for the R2-specific security configuration.\n\n## Sessions — the second redeploy-killer\n\nIf your sessions live in-process (Express `express-session` with default `MemoryStore`, Next.js naive session-in-Map), every deploy logs out every user. Same problem if you scale to two instances — half of requests land on the instance that never saw the login.\n\n```ts\n\u002F\u002F Bad — default Express in-memory session store\nimport session from 'express-session';\napp.use(session({ secret: process.env.SESSION_SECRET! }));  \u002F\u002F MemoryStore by default!\n\n\u002F\u002F Good — Redis-backed session\nimport { createClient } from 'redis';\nimport RedisStore from 'connect-redis';\n\nconst redis = createClient({ url: process.env.REDIS_URL });\nawait redis.connect();\n\napp.use(session({\n  store: new RedisStore({ client: redis }),\n  secret: process.env.SESSION_SECRET!,\n  cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 7 * 24 * 60 * 60 * 1000 },\n}));\n```\n\nStateless alternatives:\n\n- **Signed cookies** (the session payload itself is in the cookie, signed by the server). Works for small sessions; the cookie grows with the data.\n- **JWT** with short TTL + refresh tokens. See [`auth-hardening`](..\u002Fauth-hardening\u002FSKILL.md) for the tradeoffs.\n\n## Background jobs — `setTimeout` is not a queue\n\n```ts\n\u002F\u002F Bad — process is killed on deploy, job never runs\napp.post('\u002Fapi\u002Fsign-up', async (req, res) => {\n  await db.users.create(req.body);\n  setTimeout(() => sendWelcomeEmail(req.body.email), 60_000);   \u002F\u002F ☠️\n  res.json({ ok: true });\n});\n\n\u002F\u002F Good — persistent queue, retries, observability\nimport { Queue, Worker } from 'bullmq';\n\nconst emailQueue = new Queue('emails', { connection: { url: process.env.REDIS_URL }});\n\napp.post('\u002Fapi\u002Fsign-up', async (req, res) => {\n  await db.users.create(req.body);\n  await emailQueue.add('welcome', { email: req.body.email }, {\n    attempts: 5,\n    backoff: { type: 'exponential', delay: 1000 },\n    removeOnComplete: 1000,\n  });\n  res.json({ ok: true });\n});\n\n\u002F\u002F Worker — separate process, can be on the same or different host\nnew Worker('emails', async (job) => {\n  await sendWelcomeEmail(job.data.email);\n}, { connection: { url: process.env.REDIS_URL }});\n```\n\nWhat you get:\n- Retries with backoff\n- Dead-letter queue for poison messages\n- Persistence — restarting the worker does not lose jobs\n- Observable — BullMQ has an admin UI\n\nFor cron-style \"every hour\" jobs, the right place is **also** the queue (BullMQ has `repeat`, or use a dedicated cron worker), or a managed scheduler (AWS EventBridge, Cloudflare Workers Cron). Not a `setInterval` in the web process.\n\n## Deploys — immutable artifacts, health checks, graceful shutdown\n\nThree patterns that together make deploys boring:\n\n### Immutable artifacts\n\nA deploy is \"ship this exact image \u002F artifact to production.\" Not \"pull, install, configure.\" The same artifact that ran in staging runs in prod. If something breaks in prod, rolling back means pointing at the previous artifact — no re-install, no risk of a different state.\n\n- Docker image with explicit tag (`myapp:1.2.3` or SHA-digest), not `:latest`\n- Or built bundle (zip \u002F tarball) checked into a versioned artifact store\n- Build once, deploy that exact thing to every environment\n\n### Health checks\n\nTwo endpoints, two purposes:\n\n```ts\n\u002F\u002F Liveness — is the process alive? Cheap, no dependencies.\napp.get('\u002Fhealthz', (req, res) => res.json({ ok: true }));\n\n\u002F\u002F Readiness — is the process actually ready to serve traffic?\napp.get('\u002Freadyz', async (req, res) => {\n  try {\n    await Promise.all([\n      db.$queryRaw`SELECT 1`,\n      redis.ping(),\n    ]);\n    res.json({ ok: true });\n  } catch (err) {\n    res.status(503).json({ ok: false, err: String(err) });\n  }\n});\n```\n\nThe orchestrator (Docker, Kubernetes, your reverse proxy) routes traffic only when `\u002Freadyz` returns 200. Without this, new containers get traffic before they have warmed connections to the DB and produce 500s for the first 30 seconds of every deploy.\n\n### Graceful shutdown\n\nWhen the orchestrator sends `SIGTERM`, stop accepting new requests, finish in-flight ones, close connections, then exit. Most frameworks ship this; some make you wire it.\n\n```ts\nconst server = app.listen(port);\n\nconst shutdown = async (signal: string) => {\n  console.log(`${signal} — draining`);\n  server.close(async () => {\n    await redis.quit();\n    await db.$disconnect();\n    process.exit(0);\n  });\n  \u002F\u002F Hard cap — if drain takes too long, force exit\n  setTimeout(() => process.exit(1), 30_000).unref();\n};\n\nprocess.on('SIGTERM', () => shutdown('SIGTERM'));\nprocess.on('SIGINT', () => shutdown('SIGINT'));\n```\n\nCombined: zero-downtime rolling deploys become trivial.\n\n## Database operations — migrations and connections\n\n### Migrations\n\n- **Forward-compatible by default**: never break the old code. New code can run against old schema, old code can run against new schema, until both sides have rolled out.\n- **Expand-then-contract**: add a new column \u002F table first, deploy code that writes to both, backfill, then remove the old. No \"rename column\" in a single migration in production.\n- **Lock-free for large tables**: in Postgres, prefer `ADD COLUMN ... DEFAULT NULL` (instant) over `ADD COLUMN ... DEFAULT 'x' NOT NULL` (rewrites the table). Use `CREATE INDEX CONCURRENTLY` for indexes on large tables.\n- **Run migrations as a separate step**, not at app boot. Two app instances racing to run the same migration at startup is its own incident class.\n\n### Connection pooling\n\nApp processes open too many connections to Postgres by default. Postgres struggles past ~100 active connections. Use a pooler:\n\n- **PgBouncer** — battle-tested, transaction-mode for most apps\n- **Supabase, Neon, RDS Proxy** — managed pooler in front of managed Postgres\n- **Prisma Accelerate** \u002F **Drizzle's pool** — ORM-level pooling\n\nSet per-instance pool size = `(maxConnections \u002F numInstances)` − headroom. For 4 instances and a 100-connection budget, that's ~20 connections per instance with 20 spare.\n\nSee [`postgres-hardening`](..\u002Fpostgres-hardening\u002FSKILL.md) for the security side.\n\n## Idempotency — survive retries\n\nEvery state-changing operation should produce the same effect whether it runs once or ten times. This is what makes retries, queues, and replays safe.\n\n- **Webhook handlers** dedupe on the provider's event ID. See [`stripe-webhook-security`](..\u002Fstripe-webhook-security\u002FSKILL.md).\n- **Order creation** dedupes on a client-generated idempotency key (`X-Idempotency-Key` header), not on auto-incremented IDs.\n- **Email sends** dedupe on `(template, recipient, trigger-id)`.\n- **File uploads** dedupe on content hash (compute SHA-256 of the file, use as the object key).\n\nA retry storm should be boring, not catastrophic.\n\n## Observability — three pillars, minimum viable\n\nFor a small backend, \"observability\" is not a buzzword — it is three concrete things:\n\n1. **Centralized logs** — see [`log-strategy`](..\u002Flog-strategy\u002FSKILL.md). Cloud logging, Loki, hosted. Not \"ssh in to read \u002Fvar\u002Flog\".\n2. **Per-request tracing** — generate a `request_id` at the edge (Cloudflare adds one for free), thread it through every log line and every downstream service call. When something breaks, you can reconstruct the full path.\n3. **Error reporting** — Sentry \u002F Rollbar \u002F Highlight \u002F GlitchTip. Each unhandled exception lands with stack trace, breadcrumbs, user context. Without this you only see errors users actively complain about.\n\nMetrics (Prometheus \u002F Grafana \u002F Datadog) are great when traffic grows; not day-one critical.\n\n## The cost-aware tier — when to add complexity\n\nMost vibe-coded projects do not need Kubernetes, microservices, multi-region, or a service mesh. The cost of premature complexity is real: more failure modes, more \"why is this not working\" hours, more bills.\n\nReasonable trajectory:\n\n| Stage | Architecture |\n|---|---|\n| 0–1k users | Single VPS, app + Postgres + Redis colocated, daily off-host backups, Cloudflare in front |\n| 1k–10k users | Same, plus object storage for files, separate worker process, managed Postgres or DB on a dedicated VM |\n| 10k–100k users | Multiple app instances behind a load balancer, managed Postgres with read replica, queue is its own service, CDN is essential |\n| 100k+ users | Dedicated DB nodes, autoscaling app tier, regional split if latency demands, real SRE practices |\n\nSkip stages only if you have a specific reason. \"We might need Kubernetes someday\" is not a reason for today.\n\n## Twelve-Factor — the canonical reference\n\nMost of this skill is a practical application of [The Twelve-Factor App](https:\u002F\u002F12factor.net), an excellent guide written in 2011 that has aged remarkably well. The twelve factors:\n\n1. **Codebase** — one codebase tracked in revision control, many deploys\n2. **Dependencies** — explicitly declared and isolated (lockfiles)\n3. **Config** — stored in the environment, not the code\n4. **Backing services** — treated as attached resources (DB, cache, queue are configurable)\n5. **Build, release, run** — strictly separate stages\n6. **Processes** — execute the app as one or more stateless processes\n7. **Port binding** — export services via port binding (no external web server required at the app layer)\n8. **Concurrency** — scale out via the process model\n9. **Disposability** — fast startup and graceful shutdown\n10. **Dev\u002Fprod parity** — keep dev, staging, and production as similar as possible\n11. **Logs** — treat logs as event streams\n12. **Admin processes** — run admin\u002Fmanagement tasks as one-off processes\n\nRead it once. Then read it again every six months. Most \"production incidents\" in small-team backends are violations of one of these twelve.\n\n## Quick architecture review checklist\n\nBefore declaring a backend production-ready, walk through:\n\n- [ ] App processes are stateless — restarting an instance loses nothing\n- [ ] User uploads go to object storage (S3 \u002F R2 \u002F equivalent), not local disk\n- [ ] Sessions are in Redis \u002F DB \u002F signed cookies, not in-process memory\n- [ ] Background jobs run via a persistent queue, not `setTimeout` \u002F `setInterval`\n- [ ] Cron jobs run via a real scheduler, not the web process\n- [ ] Cache is explicit (Redis \u002F KV \u002F CDN), not implicit in-memory hashmaps\n- [ ] Database has off-host backups, restore-tested at least once\n- [ ] Database migrations are forward-compatible; never \"rename + drop\" in one step\n- [ ] Connection pooling is in place (PgBouncer or equivalent)\n- [ ] App has `\u002Fhealthz` (liveness) and `\u002Freadyz` (readiness) endpoints\n- [ ] App handles `SIGTERM` gracefully — drains connections, finishes in-flight work\n- [ ] Deploys produce immutable artifacts (image tag or SHA digest), no in-place mutation\n- [ ] Rollback is a single command pointing at a previous artifact\n- [ ] Logs ship to a central destination, with `request_id` threading\n- [ ] Unhandled errors land in Sentry \u002F equivalent\n- [ ] All state-changing operations are idempotent\n- [ ] Configuration is in env vars; no environment-specific values baked into the image\n- [ ] `.env` is not in the image, not in the repo\n\nIf anything is \"no\", you have an outage waiting. Fix before scaling, not after.\n\n## What this skill will not do\n\n- Tell you to use Kubernetes \u002F microservices \u002F multi-region for a project that does not need them\n- Endorse writing application data to the app server's local disk in production\n- Help build a backend whose deploys lose user data because \"we'll fix it later\"\n- Replace experience — architecture is judgment. This skill gives you the patterns; the calls are still yours\n",{"name":5,"description":7},"main","481dcd7dd2e288b9d627a2bd017db70e64e6c6fa",".claude\u002Fskills\u002Fgw360--backend-architecture",2,"https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI","https:\u002F\u002Fyana.vutam.link\u002F","https:\u002F\u002Fgithub.com\u002FHoronomos-laps","https:\u002F\u002Fyana.vutam.link","An open-source governed runtime & execution environment for multi-agent AI systems.","2026-11-14 13:24:09",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Horonomos-laps\u002FYana-AI --skill backend-architecture",{"tool":40,"command":41},"bunx","bunx skills add Horonomos-laps\u002FYana-AI --skill backend-architecture",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Horonomos-laps\u002FYana-AI --skill backend-architecture","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fgw360--backend-architecture\u002FSKILL.md",true,[],[49,57,64,72,80,88],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M735GKET5YVYKAY62W2P5YXB","openai--sentry--sentry","Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.","MIT","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fopenai--sentry--sentry\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M73DCAP83T17HY7SMGK7MGFE","ito-basket-compare","Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fito-basket-compare\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":68,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M734CYEMZFDR3KH6SW0JP8TD","implementing-network-traffic-baselining","Build network traffic baselines from NetFlow\u002FIPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly\u002Fdaily traffic pattern profiling","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":76,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M73ASZ6NJRJM44Z2P84NGQ3Q","detecting-evasion-techniques-in-endpoint-logs","Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":84,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M734AFNXD06Z78QRK0VKGT7Q","implementing-microsegmentation-with-guardicore","Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M736TK27QMCXK0DVCH25SJN5","ramdisk-tmpfs-patterns","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Framdisk-tmpfs-patterns\u002FSKILL.md",[],[]]