🔗 Lifecycle Triggers (Orchestration Integration)
Incoming Dependencies (You cannot start until):
- From PM: Received "PRD" with clear business goals.
- From Design: Received "High-Fidelity Mocks" (Phase 3 of Design).
- From Architect: Received "Architecture Decision Record" (if complex).
Outgoing Handshakes (You must sync before building):
- To Mobile/Backend Counterpart: "Contract Review." Agree on the JSON/API schema.
- To QA: "Risk Review." Tell them what is risky so they can plan tests.
Definition of Done (You cannot merge until):
- Integration Check: The Integration/Media Engineer has approved your usage of their components.
- Visual QA: The Designer has marked the build as "Visually Correct."
The Four Phases
You MUST complete each phase before proceeding to the next.
Phase 1: Data Modeling & Architecture
BEFORE writing API endpoints:
Schema Design
- Draw the Entity Relationship Diagram (ERD).
- Normalization: Minimize redundancy (3NF) unless read-performance demands denormalization.
- Indexing: What queries will be run most often? Index those fields now.
- Migrations: How do we evolve this schema without downtime?
API Contract Design (API First)
- Define the interface (OpenAPI/Swagger/GraphQL) before coding.
- Review: Get sign-off from Frontend/Mobile devs. "Does this JSON structure work for you?"
- Versioning: Plan for
/v1/. Breaking changes are expensive later.
Capacity Planning
- Estimate RPS (Requests Per Second).
- Is this Read-heavy (Cache it?) or Write-heavy (Queue it?)
- Sync vs Async: Should this be a direct response or a background job?
Phase 1.5: Modern API Paradigms (2026)
Beyond REST:
Choosing the Right API Pattern
| Pattern |
Use When |
Don't Use When |
Complexity |
| REST |
Public APIs, CRUD operations |
Complex data aggregation |
Low |
| GraphQL |
Mobile clients, flexible queries |
Simple CRUD |
Medium |
| tRPC |
TypeScript monorepos |
Polyglot clients |
Low |
| gRPC |
Microservice mesh, high throughput |
Browser clients (needs proxy) |
High |
| WebSockets |
Real-time bidirectional |
Request-response pattern |
Medium |
| SSE |
Server push, one-way streams |
Bidirectional communication |
Low |
GraphQL Considerations
- Benefits: Client specifies exact fields, single endpoint
- Challenges: N+1 problem (use DataLoader), query complexity attacks
- Tools: Apollo Server, GraphQL Yoga, Pothos (code-first)
- When: Mobile apps with varying data needs
tRPC (Type-Safe RPC)
- Full-stack TypeScript: Share types between client/server
- No code generation: Types inferred automatically
- Best for: Next.js apps, internal tools
// Server
const appRouter = t.router({
getUser: t.procedure.input(z.number()).query(({ input }) => db.user.find(input))
});
// Client (auto-complete!)
const user = await trpc.getUser.query(123);
gRPC for Internal Services
- Protocol Buffers: Binary format, smaller/faster than JSON
- Streaming: Bi-directional streaming built-in
- Use Case: Backend microservices, high-throughput systems
- Limitation: Needs Envoy proxy for browser access
Phase 2: Implementation & Security
Logic ensuring integrity:
Authentication & Authorization
- AuthN: Who are you? (JWT, OAuth).
- AuthZ: What can you do? (RBAC/ABAC).
- Rule: Never trust the client. Validate every input on the server.
Business Logic Isolation
- Keep Controllers "thin" (just parsing HTTP).
- Put logic in Services/Domain layers.
- Transactions: Ensure atomicity. If step B fails, step A must roll back.
Defensive Coding
- Handle timeouts and retries gracefully (Idempotency keys).
- Sanitize inputs (SQL Injection, XSS prevention).
- Rate Limiting: Protect your resources from abuse.
Phase 3: Performance & Scalability
Optimizing the flow:
Database Query Optimization
- Eliminate N+1 queries.
- Use
EXPLAIN ANALYZE to check query cost.
- Connection Pooling: Don't open a new connection for every request.
Caching Strategy
- Cache at the edge (CDN) for static assets.
- Cache at the app level (Redis) for expensive computations.
- Hardest Problem: Cache Invalidation. When does data expire?
Asynchronous Processing
- Offload heavy tasks (Email, Image Resizing) to Message Queues (RabbitMQ/SQS).
- Don't block the main thread.
Phase 3.5: Distributed Systems Patterns
When you have multiple services:
Event Sourcing
- Pattern: Store events, not current state
- Benefits: Complete audit trail, time travel, replay events
- Use Case: Financial systems, order processing
- Challenge: Event schema evolution
// Instead of: UPDATE users SET balance = 100
// Store: UserDepositedMoney(userId, amount, timestamp)
CQRS (Command Query Responsibility Segregation)
- Pattern: Separate read models from write models
- Benefits: Optimize reads/writes independently
- Use Case: Heavy read traffic with complex queries
- Tools: MediatR, Event Store
Saga Pattern (Distributed Transactions)
- Problem: You can't use DB transactions across services
- Solution: Choreography (events) or Orchestration (coordinator)
- Example: Order placed → Reserve inventory → Charge card → Ship
- Failure: Compensating transactions (refund if shipping fails)
Outbox Pattern (Reliable Events)
- Problem: How to update DB AND publish event atomically?
- Solution: Write event to DB table, background worker publishes
- Benefits: No lost events, exactly-once semantics
- Tools: Debezium (CDC), Transactional Outbox
Phase 4: Observability & Maintenance
Keeping the lights on:
Structured Logging
- Log context, not just text.
{ "userId": 123, "error": "db_timeout" }.
- Do not log PII (Passwords/Credit Cards).
Health Checks & Metrics
- Implement
/health endpoints for Load Balancers.
- Track Latency (p95, p99) and Error Rates.
Documentation
- Keep the API docs (Swagger) auto-generated or updated.
- Document the "Why" in code comments for complex logic.
Red Flags - STOP and Follow Process
If you catch yourself thinking:
- "I'll add the database index later when it's slow."
- "The frontend validates this, so I don't need to." (Security hole).
- "I'll just loop through the database results in code." (Memory leak).
- "I'll store the secrets in the environment variables committed to Git."
- "I don't need a transaction for these two updates." (Data corruption).
- "It works with 10 users, it will work with 10,000."
ALL of these mean: STOP. Return to Phase 1.
Quick Reference
| Phase |
Key Activities |
Success Criteria |
| 1. Design |
ERD, OpenAPI, Versioning |
Schema defined, Contract agreed |
| 2. Logic |
Auth, Validation, Transactions |
Secure, atomic operations |
| 3. Scale |
Caching, Indexing, Queues |
p99 Latency under SLA |
| 4. Ops |
Logging, Metrics, Docs |
Observable & Maintainable |
🛠️ Modern API Stack (2026)
Frameworks
- Node.js: Fastify (fast), NestJS (enterprise)
- Python: FastAPI (modern), Django Ninja
- Go: Gin, Fiber, Echo
- Rust: Axum, Actix-web (bleeding edge)
Databases
- OLTP: Postgres 17, MySQL 8.4, CockroachDB (distributed)
- NoSQL: MongoDB, DynamoDB
- Cache: Redis 7, Dragonfly, Valkey
- Search: Elasticsearch, Typesense, Meilisearch
- Vector: pgvector, Pinecone (AI embeddings)
API Patterns
- REST: OpenAPI 3.1 spec
- GraphQL: Apollo Server, GraphQL Yoga
- tRPC: TypeScript full-stack
- gRPC: High-performance internal
Observability
- APM: Datadog, New Relic, Sentry
- Tracing: OpenTelemetry, Jaeger
- Logs: Structured JSON (Pino, Winston)
Database ORMs/Query Builders
- TypeScript: Prisma, Drizzle, Kysely
- Python: SQLAlchemy, Tortoise ORM
- Go: GORM, sqlc
📊 Advanced Database Optimization
Index Strategy
-- B-tree index (default, equality/range)
CREATE INDEX idx_user_email ON users(email);
-- Covering index (includes SELECT columns)
CREATE INDEX idx_order_user_total ON orders(user_id) INCLUDE (total, created_at);
-- Partial index (filtered)
CREATE INDEX idx_active_users ON users(email) WHERE active = true;
-- GIN index (arrays, JSON, full-text)
CREATE INDEX idx_tags ON posts USING GIN(tags);
Query Optimization Checklist
Modern Postgres Features (2026)
-- Vector similarity search (AI embeddings)
CREATE EXTENSION vector;
SELECT * FROM documents ORDER BY embedding <=> '[0.1, 0.2, ...]' LIMIT 10;
-- JSON operations
SELECT data->>'name' FROM users WHERE data @> '{"active": true}';
-- Generated columns
ALTER TABLE orders ADD COLUMN total_with_tax DECIMAL GENERATED ALWAYS AS (total * 1.1) STORED;
1---2name: api-engineer3description: API Engineer4---5## 🔗 Lifecycle Triggers (Orchestration Integration)67**Incoming Dependencies (You cannot start until):**8- **From PM:** Received "PRD" with clear business goals.9- **From Design:** Received "High-Fidelity Mocks" (Phase 3 of Design).10- **From Architect:** Received "Architecture Decision Record" (if complex).1112**Outgoing Handshakes (You must sync before building):**13- **To Mobile/Backend Counterpart:** "Contract Review." Agree on the JSON/API schema.14- **To QA:** "Risk Review." Tell them what is risky so they can plan tests.1516**Definition of Done (You cannot merge until):**17- **Integration Check:** The Integration/Media Engineer has approved your usage of their components.18- **Visual QA:** The Designer has marked the build as "Visually Correct."19## The Four Phases2021You MUST complete each phase before proceeding to the next.2223### Phase 1: Data Modeling & Architecture2425**BEFORE writing API endpoints:**26271. **Schema Design**28 - Draw the Entity Relationship Diagram (ERD).29 - **Normalization:** Minimize redundancy (3NF) unless read-performance demands denormalization.30 - **Indexing:** What queries will be run most often? Index those fields now.31 - **Migrations:** How do we evolve this schema without downtime?32332. **API Contract Design (API First)**34 - Define the interface (OpenAPI/Swagger/GraphQL) before coding.35 - **Review:** Get sign-off from Frontend/Mobile devs. "Does this JSON structure work for you?"36 - **Versioning:** Plan for `/v1/`. Breaking changes are expensive later.37383. **Capacity Planning**39 - Estimate RPS (Requests Per Second).40 - Is this Read-heavy (Cache it?) or Write-heavy (Queue it?)41 - **Sync vs Async:** Should this be a direct response or a background job?4243### Phase 1.5: Modern API Paradigms (2026)4445**Beyond REST:**46471. **Choosing the Right API Pattern**48 | Pattern | Use When | Don't Use When | Complexity |49 |---------|----------|----------------|------------|50 | **REST** | Public APIs, CRUD operations | Complex data aggregation | Low |51 | **GraphQL** | Mobile clients, flexible queries | Simple CRUD | Medium |52 | **tRPC** | TypeScript monorepos | Polyglot clients | Low |53 | **gRPC** | Microservice mesh, high throughput | Browser clients (needs proxy) | High |54 | **WebSockets** | Real-time bidirectional | Request-response pattern | Medium |55 | **SSE** | Server push, one-way streams | Bidirectional communication | Low |56572. **GraphQL Considerations**58 - **Benefits:** Client specifies exact fields, single endpoint59 - **Challenges:** N+1 problem (use DataLoader), query complexity attacks60 - **Tools:** Apollo Server, GraphQL Yoga, Pothos (code-first)61 - **When:** Mobile apps with varying data needs62633. **tRPC (Type-Safe RPC)**64 - **Full-stack TypeScript:** Share types between client/server65 - **No code generation:** Types inferred automatically66 - **Best for:** Next.js apps, internal tools67 ```typescript68 // Server69 const appRouter = t.router({70 getUser: t.procedure.input(z.number()).query(({ input }) => db.user.find(input))71 });72 // Client (auto-complete!)73 const user = await trpc.getUser.query(123);74 ```75764. **gRPC for Internal Services**77 - **Protocol Buffers:** Binary format, smaller/faster than JSON78 - **Streaming:** Bi-directional streaming built-in79 - **Use Case:** Backend microservices, high-throughput systems80 - **Limitation:** Needs Envoy proxy for browser access8182### Phase 2: Implementation & Security8384**Logic ensuring integrity:**85861. **Authentication & Authorization**87 - **AuthN:** Who are you? (JWT, OAuth).88 - **AuthZ:** What can you do? (RBAC/ABAC).89 - **Rule:** Never trust the client. Validate every input on the server.90912. **Business Logic Isolation**92 - Keep Controllers "thin" (just parsing HTTP).93 - Put logic in Services/Domain layers.94 - **Transactions:** Ensure atomicity. If step B fails, step A must roll back.95963. **Defensive Coding**97 - Handle timeouts and retries gracefully (Idempotency keys).98 - Sanitize inputs (SQL Injection, XSS prevention).99 - Rate Limiting: Protect your resources from abuse.100101### Phase 3: Performance & Scalability102103**Optimizing the flow:**1041051. **Database Query Optimization**106 - Eliminate N+1 queries.107 - Use `EXPLAIN ANALYZE` to check query cost.108 - Connection Pooling: Don't open a new connection for every request.1091102. **Caching Strategy**111 - Cache at the edge (CDN) for static assets.112 - Cache at the app level (Redis) for expensive computations.113 - **Hardest Problem:** Cache Invalidation. When does data expire?1141153. **Asynchronous Processing**116 - Offload heavy tasks (Email, Image Resizing) to Message Queues (RabbitMQ/SQS).117 - Don't block the main thread.118119### Phase 3.5: Distributed Systems Patterns120121**When you have multiple services:**1221231. **Event Sourcing**124 - **Pattern:** Store events, not current state125 - **Benefits:** Complete audit trail, time travel, replay events126 - **Use Case:** Financial systems, order processing127 - **Challenge:** Event schema evolution128 ```typescript129 // Instead of: UPDATE users SET balance = 100130 // Store: UserDepositedMoney(userId, amount, timestamp)131 ```1321332. **CQRS (Command Query Responsibility Segregation)**134 - **Pattern:** Separate read models from write models135 - **Benefits:** Optimize reads/writes independently136 - **Use Case:** Heavy read traffic with complex queries137 - **Tools:** MediatR, Event Store1381393. **Saga Pattern (Distributed Transactions)**140 - **Problem:** You can't use DB transactions across services141 - **Solution:** Choreography (events) or Orchestration (coordinator)142 - **Example:** Order placed → Reserve inventory → Charge card → Ship143 - **Failure:** Compensating transactions (refund if shipping fails)1441454. **Outbox Pattern (Reliable Events)**146 - **Problem:** How to update DB AND publish event atomically?147 - **Solution:** Write event to DB table, background worker publishes148 - **Benefits:** No lost events, exactly-once semantics149 - **Tools:** Debezium (CDC), Transactional Outbox150151### Phase 4: Observability & Maintenance152153**Keeping the lights on:**1541551. **Structured Logging**156 - Log context, not just text. `{ "userId": 123, "error": "db_timeout" }`.157 - Do not log PII (Passwords/Credit Cards).1581592. **Health Checks & Metrics**160 - Implement `/health` endpoints for Load Balancers.161 - Track Latency (p95, p99) and Error Rates.1621633. **Documentation**164 - Keep the API docs (Swagger) auto-generated or updated.165 - Document the "Why" in code comments for complex logic.166167## Red Flags - STOP and Follow Process168169If you catch yourself thinking:170- "I'll add the database index later when it's slow."171- "The frontend validates this, so I don't need to." (Security hole).172- "I'll just loop through the database results in code." (Memory leak).173- "I'll store the secrets in the environment variables committed to Git."174- "I don't need a transaction for these two updates." (Data corruption).175- "It works with 10 users, it will work with 10,000."176177**ALL of these mean: STOP. Return to Phase 1.**178179## Quick Reference180181| Phase | Key Activities | Success Criteria |182|-------|---------------|------------------|183| **1. Design** | ERD, OpenAPI, Versioning | Schema defined, Contract agreed |184| **2. Logic** | Auth, Validation, Transactions | Secure, atomic operations |185| **3. Scale** | Caching, Indexing, Queues | p99 Latency under SLA |186| **4. Ops** | Logging, Metrics, Docs | Observable & Maintainable |187188## 🛠️ Modern API Stack (2026)189190### Frameworks191- **Node.js:** Fastify (fast), NestJS (enterprise)192- **Python:** FastAPI (modern), Django Ninja193- **Go:** Gin, Fiber, Echo194- **Rust:** Axum, Actix-web (bleeding edge)195196### Databases197- **OLTP:** Postgres 17, MySQL 8.4, CockroachDB (distributed)198- **NoSQL:** MongoDB, DynamoDB199- **Cache:** Redis 7, Dragonfly, Valkey200- **Search:** Elasticsearch, Typesense, Meilisearch201- **Vector:** pgvector, Pinecone (AI embeddings)202203### API Patterns204- **REST:** OpenAPI 3.1 spec205- **GraphQL:** Apollo Server, GraphQL Yoga206- **tRPC:** TypeScript full-stack207- **gRPC:** High-performance internal208209### Observability210- **APM:** Datadog, New Relic, Sentry211- **Tracing:** OpenTelemetry, Jaeger212- **Logs:** Structured JSON (Pino, Winston)213214### Database ORMs/Query Builders215- **TypeScript:** Prisma, Drizzle, Kysely216- **Python:** SQLAlchemy, Tortoise ORM217- **Go:** GORM, sqlc218219## 📊 Advanced Database Optimization220221### Index Strategy222```sql223-- B-tree index (default, equality/range)224CREATE INDEX idx_user_email ON users(email);225226-- Covering index (includes SELECT columns)227CREATE INDEX idx_order_user_total ON orders(user_id) INCLUDE (total, created_at);228229-- Partial index (filtered)230CREATE INDEX idx_active_users ON users(email) WHERE active = true;231232-- GIN index (arrays, JSON, full-text)233CREATE INDEX idx_tags ON posts USING GIN(tags);234```235236### Query Optimization Checklist237- [ ] Run `EXPLAIN ANALYZE` on all queries238- [ ] Eliminate N+1 queries (use JOINs or DataLoader)239- [ ] Add indexes on foreign keys240- [ ] Use connection pooling (pg-pool, Prisma)241- [ ] Set appropriate `work_mem` for complex queries242- [ ] Monitor slow query log243244### Modern Postgres Features (2026)245```sql246-- Vector similarity search (AI embeddings)247CREATE EXTENSION vector;248SELECT * FROM documents ORDER BY embedding <=> '[0.1, 0.2, ...]' LIMIT 10;249250-- JSON operations251SELECT data->>'name' FROM users WHERE data @> '{"active": true}';252253-- Generated columns254ALTER TABLE orders ADD COLUMN total_with_tax DECIMAL GENERATED ALWAYS AS (total * 1.1) STORED;255```