Engineering Advanced
Advanced engineering patterns for AI-native startups building agents, RAG systems, APIs, and scalable infrastructure.
Keywords
Agent design, RAG, retrieval augmented generation, MCP, API design, REST, GraphQL, CI/CD, GitHub Actions, Docker, Kubernetes, microservices, event-driven, message queues, caching, database design, system design, observability, infrastructure as code, AI pipeline
Core Domains
1. Agent Design
Agent architecture patterns:
| Pattern |
Use Case |
Complexity |
| Single agent + tools |
Simple tasks, clear workflow |
Low |
| Agent with sub-agents |
Complex tasks, domain separation |
Medium |
| Agent team (orchestrator) |
Multi-domain, parallel work |
High |
| Agent swarm |
Autonomous exploration, research |
Very High |
Agent design principles:
- Give agents clear, specific instructions (not vague goals)
- Define tool boundaries (what the agent CAN and CANNOT do)
- Implement guardrails (content filters, action limits, human-in-the-loop)
- Design for failure (retry logic, fallback paths, error handling)
- Observe everything (log prompts, responses, tool calls, latency)
Agent evaluation:
- Task completion rate
- Average tokens per task
- Tool call efficiency (fewer calls = better)
- Error rate and recovery success
- User satisfaction / output quality
2. RAG Architecture
RAG pipeline components:
Documents → Chunking → Embedding → Vector Store → Retrieval → Generation
Chunking strategies:
| Strategy |
Best For |
Chunk Size |
| Fixed-size |
Simple docs, consistent structure |
256-512 tokens |
| Semantic |
Complex docs, mixed content |
Variable |
| Recursive |
Hierarchical content |
Parent + child |
| Document-level |
Short docs, complete context needed |
Full document |
Retrieval optimization:
- Hybrid search: Vector similarity + keyword (BM25)
- Re-ranking: Cross-encoder after initial retrieval
- Metadata filtering: Pre-filter by date, source, category
- Query expansion: Generate multiple query variations
- Contextual compression: Summarize retrieved chunks
Vector databases:
| Database |
Self-hosted |
Cloud |
Best For |
| pgvector |
Yes |
Supabase, Neon |
Already using PostgreSQL |
| Pinecone |
No |
Yes |
Managed, serverless |
| Weaviate |
Yes |
Yes |
Multi-modal, hybrid search |
| Qdrant |
Yes |
Yes |
Performance, filtering |
| ChromaDB |
Yes |
No |
Prototyping, local dev |
RAG quality metrics:
- Retrieval precision: % of retrieved chunks that are relevant
- Retrieval recall: % of relevant chunks that are retrieved
- Faithfulness: Does the answer match the retrieved context?
- Answer relevancy: Does the answer address the question?
3. API Design
REST API design rules:
- Use nouns for resources (
/users, not /getUsers)
- HTTP methods: GET (read), POST (create), PUT (replace), PATCH (update), DELETE
- Consistent naming:
snake_case for JSON, plural nouns for collections
- Pagination: Cursor-based for real-time data, offset for static
- Versioning: URL path (
/v1/) preferred over headers
- Error responses: Consistent format with error code, message, details
API response format:
{
"data": { ... },
"meta": { "page": 1, "total": 100 },
"errors": null
}
Error response format:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is required",
"details": [{ "field": "email", "issue": "missing" }]
}
}
Rate limiting:
- Return
429 Too Many Requests with Retry-After header
- Implement per-user and per-IP limits
- Use sliding window algorithm
- Document limits clearly in API docs
4. CI/CD Pipeline Architecture
Pipeline stages:
Push → Lint → Test → Build → Security Scan → Deploy (Staging) → Deploy (Production)
GitHub Actions best practices:
- Cache dependencies (node_modules, pip cache)
- Run tests in parallel where possible
- Use matrix builds for multiple environments
- Pin action versions (don't use
@latest)
- Store secrets in GitHub Secrets, not in code
- Keep workflows DRY with reusable workflows
Deployment strategies:
| Strategy |
Risk |
Complexity |
Best For |
| Direct deploy |
High |
Low |
Internal tools, early stage |
| Blue/Green |
Low |
Medium |
Zero-downtime deploys |
| Canary |
Low |
High |
High-traffic production |
| Feature flags |
Very Low |
Medium |
Gradual rollout |
5. MCP Server Building
MCP (Model Context Protocol) server structure:
- Define tools with clear names and descriptions
- Input schemas using JSON Schema
- Handle errors gracefully with informative messages
- Implement authentication if accessing external services
- Test with Claude Code or Claude Desktop
MCP tool design principles:
- One tool, one job (Single Responsibility)
- Clear parameter names and descriptions
- Return structured data (JSON), not prose
- Include examples in tool descriptions
- Handle edge cases (empty results, timeout, rate limits)
6. Observability
Three pillars:
- Logs: Structured (JSON), with correlation IDs, appropriate levels
- Metrics: Business metrics (conversions, revenue), technical metrics (latency, error rate)
- Traces: Distributed tracing across services (OpenTelemetry)
Essential alerts:
- Error rate > X% for Y minutes
- P99 latency > Xms
- CPU/Memory > 80% sustained
- Queue depth growing
- 5xx responses from dependencies
Tool recommendations:
- Logging: Structured logging → Datadog, Grafana Loki, CloudWatch
- Metrics: Prometheus + Grafana, Datadog
- Tracing: OpenTelemetry → Jaeger, Datadog
- Error tracking: Sentry
- Uptime: Betteruptime, Checkly
Reference Files
references/agent-design.md — Agent architecture, evaluation, prompt engineering
references/rag-architecture.md — RAG pipeline design, chunking, retrieval optimization
references/api-design.md — REST/GraphQL patterns, versioning, error handling
references/cicd.md — Pipeline architecture, deployment strategies, GitHub Actions
references/mcp-builder.md — MCP server development, tool design, testing
1---2name: engineering-advanced3description: Advanced engineering patterns for AI-native products. Use when the user mentions agent design, RAG architecture, AI pipelines, MCP servers, API design best practices, CI/CD pipeline architecture, system design interviews, observability, infrastructure as code, or advanced engineering topics. Also triggers on: agent, RAG, retrieval augmented generation, MCP, API design, REST, GraphQL, CI/CD, GitHub Actions, Docker, Kubernetes, microservices architecture, event-driven, message queues, caching strategies, database design, system design.4---56# Engineering Advanced78Advanced engineering patterns for AI-native startups building agents, RAG systems, APIs, and scalable infrastructure.910## Keywords1112Agent design, RAG, retrieval augmented generation, MCP, API design, REST, GraphQL, CI/CD, GitHub Actions, Docker, Kubernetes, microservices, event-driven, message queues, caching, database design, system design, observability, infrastructure as code, AI pipeline1314## Core Domains1516### 1. Agent Design1718**Agent architecture patterns:**1920| Pattern | Use Case | Complexity |21|---------|----------|------------|22| Single agent + tools | Simple tasks, clear workflow | Low |23| Agent with sub-agents | Complex tasks, domain separation | Medium |24| Agent team (orchestrator) | Multi-domain, parallel work | High |25| Agent swarm | Autonomous exploration, research | Very High |2627**Agent design principles:**28- Give agents clear, specific instructions (not vague goals)29- Define tool boundaries (what the agent CAN and CANNOT do)30- Implement guardrails (content filters, action limits, human-in-the-loop)31- Design for failure (retry logic, fallback paths, error handling)32- Observe everything (log prompts, responses, tool calls, latency)3334**Agent evaluation:**35- Task completion rate36- Average tokens per task37- Tool call efficiency (fewer calls = better)38- Error rate and recovery success39- User satisfaction / output quality4041### 2. RAG Architecture4243**RAG pipeline components:**4445```46Documents → Chunking → Embedding → Vector Store → Retrieval → Generation47```4849**Chunking strategies:**5051| Strategy | Best For | Chunk Size |52|----------|----------|------------|53| Fixed-size | Simple docs, consistent structure | 256-512 tokens |54| Semantic | Complex docs, mixed content | Variable |55| Recursive | Hierarchical content | Parent + child |56| Document-level | Short docs, complete context needed | Full document |5758**Retrieval optimization:**59- Hybrid search: Vector similarity + keyword (BM25)60- Re-ranking: Cross-encoder after initial retrieval61- Metadata filtering: Pre-filter by date, source, category62- Query expansion: Generate multiple query variations63- Contextual compression: Summarize retrieved chunks6465**Vector databases:**6667| Database | Self-hosted | Cloud | Best For |68|----------|------------|-------|----------|69| pgvector | Yes | Supabase, Neon | Already using PostgreSQL |70| Pinecone | No | Yes | Managed, serverless |71| Weaviate | Yes | Yes | Multi-modal, hybrid search |72| Qdrant | Yes | Yes | Performance, filtering |73| ChromaDB | Yes | No | Prototyping, local dev |7475**RAG quality metrics:**76- Retrieval precision: % of retrieved chunks that are relevant77- Retrieval recall: % of relevant chunks that are retrieved78- Faithfulness: Does the answer match the retrieved context?79- Answer relevancy: Does the answer address the question?8081### 3. API Design8283**REST API design rules:**84- Use nouns for resources (`/users`, not `/getUsers`)85- HTTP methods: GET (read), POST (create), PUT (replace), PATCH (update), DELETE86- Consistent naming: `snake_case` for JSON, plural nouns for collections87- Pagination: Cursor-based for real-time data, offset for static88- Versioning: URL path (`/v1/`) preferred over headers89- Error responses: Consistent format with error code, message, details9091**API response format:**92```json93{94 "data": { ... },95 "meta": { "page": 1, "total": 100 },96 "errors": null97}98```99100**Error response format:**101```json102{103 "error": {104 "code": "VALIDATION_ERROR",105 "message": "Email is required",106 "details": [{ "field": "email", "issue": "missing" }]107 }108}109```110111**Rate limiting:**112- Return `429 Too Many Requests` with `Retry-After` header113- Implement per-user and per-IP limits114- Use sliding window algorithm115- Document limits clearly in API docs116117### 4. CI/CD Pipeline Architecture118119**Pipeline stages:**120```121Push → Lint → Test → Build → Security Scan → Deploy (Staging) → Deploy (Production)122```123124**GitHub Actions best practices:**125- Cache dependencies (node_modules, pip cache)126- Run tests in parallel where possible127- Use matrix builds for multiple environments128- Pin action versions (don't use `@latest`)129- Store secrets in GitHub Secrets, not in code130- Keep workflows DRY with reusable workflows131132**Deployment strategies:**133134| Strategy | Risk | Complexity | Best For |135|----------|------|------------|----------|136| Direct deploy | High | Low | Internal tools, early stage |137| Blue/Green | Low | Medium | Zero-downtime deploys |138| Canary | Low | High | High-traffic production |139| Feature flags | Very Low | Medium | Gradual rollout |140141### 5. MCP Server Building142143**MCP (Model Context Protocol) server structure:**144- Define tools with clear names and descriptions145- Input schemas using JSON Schema146- Handle errors gracefully with informative messages147- Implement authentication if accessing external services148- Test with Claude Code or Claude Desktop149150**MCP tool design principles:**151- One tool, one job (Single Responsibility)152- Clear parameter names and descriptions153- Return structured data (JSON), not prose154- Include examples in tool descriptions155- Handle edge cases (empty results, timeout, rate limits)156157### 6. Observability158159**Three pillars:**1601. **Logs:** Structured (JSON), with correlation IDs, appropriate levels1612. **Metrics:** Business metrics (conversions, revenue), technical metrics (latency, error rate)1623. **Traces:** Distributed tracing across services (OpenTelemetry)163164**Essential alerts:**165- Error rate > X% for Y minutes166- P99 latency > Xms167- CPU/Memory > 80% sustained168- Queue depth growing169- 5xx responses from dependencies170171**Tool recommendations:**172- Logging: Structured logging → Datadog, Grafana Loki, CloudWatch173- Metrics: Prometheus + Grafana, Datadog174- Tracing: OpenTelemetry → Jaeger, Datadog175- Error tracking: Sentry176- Uptime: Betteruptime, Checkly177178## Reference Files179180- `references/agent-design.md` — Agent architecture, evaluation, prompt engineering181- `references/rag-architecture.md` — RAG pipeline design, chunking, retrieval optimization182- `references/api-design.md` — REST/GraphQL patterns, versioning, error handling183- `references/cicd.md` — Pipeline architecture, deployment strategies, GitHub Actions184- `references/mcp-builder.md` — MCP server development, tool design, testing