agentleFS
mchittinenimchittineni/cloud-platform-skills/.cursor/rules/skills/cloud-native-microservices-patterns.mdc

cloud-platform-skills / skills

Cursor rule1 starsChanged 3 months agoMITView on GitHub

Cloud-native service design: 12-factor compliance, liveness, readiness and startup probes, graceful shutdown with SIGTERM handling and connection draining, structured logging with correlation IDs, and idempotency. Use when pods are killed during a deploy and drop in-flight requests, when Kubernetes restarts a container that is merely slow to start, or when refactoring a service to run correctly on Kubernetes.

  • Reads credentials

The file

We split this cloud-native-microservices-patterns.mdc into the rules it gives an agent

6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Backing Services: Treat databases, caches, and queues as attached resources.

    line 28
  2. Distinctive:

    Dev/Prod Parity: Keep development, staging, and production as similar as possible.

    line 34
  3. Very specific:

    Logs: Treat logs as unbuffered event streams (stdout/stderr in JSON format).

    line 35
  4. Distinctive:

    Admin Processes: Run admin/management tasks as one-off processes (K8s Jobs).

    line 36
  5. Very specific:

    Do: Always implement both livenessProbe (is the process deadlocked?) and readinessProbe (is the app ready to serve traffic?).

    line 70
  6. Very specific:

    Don't: Never exit immediately upon receiving SIGTERM.

    line 71

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
cloud-native-microservices-patterns.mdc
---
description: "Cloud-native service design: 12-factor compliance, liveness, readiness and startup probes, graceful shutdown with SIGTERM handling and connection draining, structured logging with correlation IDs, and idempotency. Use when pods are killed during a deploy and drop in-flight requests, when Kubernetes restarts a container that is merely slow to start, or when refactoring a service to run correctly on Kubernetes."
globs:
alwaysApply: false
---

# Cloud Native Architecture & 12-Factor Microservices Patterns

## When to Use This Skill

**Triggers — load this skill when:**

- A service is being designed or refactored for Kubernetes
- Probes, shutdown handling, or connection draining behave incorrectly
- Logging, config, or state handling violates 12-factor and hurts operability

**Route elsewhere when:**

- Manifest and chart mechanics -> `helm-kubernetes-deployment`
- Inter-service traffic policy -> `api-gateway-service-mesh`
- Event-driven decomposition -> `serverless-event-driven-architecture`

## 1. 12-Factor Production Checklist for Microservices

- **Codebase**: One codebase tracked in revision control, many deploys.
- **Dependencies**: Explicitly declare and isolate dependencies (lockfiles, container layers).
- **Config**: Store configuration in the environment (`process.env`, `os.environ`), never in code.
- **Backing Services**: Treat databases, caches, and queues as attached resources.
- **Build, Release, Run**: Strict separation between build stage and execution stage.
- **Processes**: Execute the app as one or more stateless, shareable processes.
- **Port Binding**: Export services via port binding (e.g. `:8080`).
- **Concurrency**: Scale out via the process model (horizontal pod scaling).
- **Disposability**: Maximize robustness with fast startup and graceful shutdown (`SIGTERM` handling).
- **Dev/Prod Parity**: Keep development, staging, and production as similar as possible.
- **Logs**: Treat logs as unbuffered event streams (`stdout`/`stderr` in JSON format).
- **Admin Processes**: Run admin/management tasks as one-off processes (K8s Jobs).

---

## 2. Graceful Shutdown Implementation (Node.js / Express Example)

```javascript
const server = app.listen(process.env.PORT || 8080);

const shutdown = (signal) => {
  console.log(`Received ${signal}. Gracefully closing HTTP server...`);
  server.close(() => {
    console.log('HTTP server closed. Disconnecting database pools...');
    db.pool.end(() => {
      console.log('Database pool closed. Exiting process.');
      process.exit(0);
    });
  });

  // Force shutdown after 15s timeout
  setTimeout(() => {
    console.error('Graceful shutdown timeout exceeded. Forcing exit.');
    process.exit(1);
  }, 15000);
};

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
```

---

## 3. Best Practices & Anti-Patterns

- **Do**: Always implement both `livenessProbe` (is the process deadlocked?) and `readinessProbe` (is the app ready to serve traffic?).
- **Don't**: Never exit immediately upon receiving `SIGTERM`; allow in-flight HTTP requests 5-15 seconds to drain.

---

## 4. Graceful Shutdown Timing & Request Correlation

Dropped requests during a deploy are almost always a **race**: Kubernetes sends `SIGTERM` and
removes the pod from Endpoints at the same time, and in-flight proxies still hold the old
address for a moment.

The sequence that does not drop traffic:

1. `preStop` sleeps (5–10s) so Endpoint removal propagates to every proxy **before** shutdown
   starts;
2. `SIGTERM` flips readiness to false and stops accepting new connections;
3. in-flight requests drain, with a deadline shorter than the grace period;
4. the process exits before `terminationGracePeriodSeconds` expires — otherwise `SIGKILL`
   truncates whatever is still running.

```yaml
spec:
  terminationGracePeriodSeconds: 45      # must exceed preStop + drain deadline
  containers:
    - name: api
      lifecycle:
        preStop:
          exec: { command: ["/bin/sh", "-c", "sleep 10"] }
      startupProbe:                       # slow boot must not be read as "wedged"
        httpGet: { path: /healthz, port: 8080 }
        failureThreshold: 30
        periodSeconds: 5
```

```javascript
process.on('SIGTERM', async () => {
  isReady = false;                                    // readiness flips first
  server.closeIdleConnections?.();
  await new Promise((r) => server.close(r));          // stop accepting, drain in-flight
  await Promise.race([pool.end(), sleep(10_000)]);    // bounded dependency close
  process.exit(0);
});
```

**Correlation IDs** make the resulting logs usable: accept `traceparent` (or `X-Request-Id`),
generate one when absent, propagate it on every outbound call, and emit it as a field on every
structured log line — `trace_id` in logs is what turns three services' logs into one story, and
it is the join key back to the trace.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.