Every principle, pattern, standard, and approach you need to build production-grade backend systems in .NET, Python, and Rust — structured, searchable, and FBT-grade.
A class should have only one reason to change. Each module should be responsible for a single user, actor, or role.
Improves maintainability, testability, and modularity. Reduces coupling and makes code changes less risky.
When designing class responsibilities and determining where to place business logic.
O
Open/Closed Principle
Software entities should be open for extension but closed for modification. Add new behavior through extension, not by changing existing code.
Reduces risk of breaking existing functionality when adding new features. Encourages flexible design.
When you need to add new features without touching stable code. Use interfaces and inheritance.
L
Liskov Substitution Principle
Derived classes must be substitutable for their base classes without breaking the contract. Objects of derived classes should work seamlessly where base class objects are expected.
Ensures type safety and prevents unexpected runtime errors. Enables polymorphism to work correctly.
When designing inheritance hierarchies and interface implementations. Check that subtypes honor parent contracts.
I
Interface Segregation Principle
Clients should not be forced to depend on interfaces they do not use. Prefer many small, specific interfaces over large, general ones.
Reduces coupling between components. Clients only depend on what they actually need.
When defining interfaces and abstract contracts. Split large interfaces into smaller, focused ones.
D
Dependency Inversion Principle
High-level modules should not depend on low-level modules; both should depend on abstractions. Depend on abstractions, not concrete implementations.
Decouples layers and components. Makes testing easier through mocking and dependency injection.
When organizing application architecture. Use DI containers to manage dependencies.
DRY
Don't Repeat Yourself
Every piece of knowledge should have a single, unambiguous representation in the system. Avoid duplicating logic, data, or intent.
Reduces bugs by centralizing logic. Changes only need to happen in one place. Improves maintainability.
When writing code, refactor duplication into reusable functions, classes, or utilities.
KISS
Keep It Simple, Stupid
Design and implement using the simplest approach that solves the problem. Avoid unnecessary complexity, abstraction, or sophistication.
Simpler code is easier to understand, debug, and maintain. Reduces cognitive load.
During design and implementation. Choose straightforward solutions before considering complex alternatives.
YAGNI
You Aren't Gonna Need It
Do not add functionality until it is explicitly required. Avoid speculative development of features "just in case."
Reduces code bloat and maintenance burden. Keeps the codebase lean and focused.
When tempted to add "future-proofing" features. Build only what is needed now.
SoC
Separation of Concerns
Divide the program into distinct sections, each handling a specific concern or responsibility. Different parts should manage different aspects (UI, business logic, data access).
Improves modularity, testability, and reusability. Makes code easier to understand and modify.
In overall application architecture. Separate presentation, business logic, and data persistence layers.
LoD
Law of Demeter
An object should only communicate with its direct dependencies, not with the dependencies of its dependencies. Avoid chained method calls like obj.a().b().c().
Reduces coupling and brittleness. Changes to intermediate objects don't break callers.
When designing object interactions and method interfaces. Keep call chains shallow.
CQS
Command Query Separation
Methods should either perform an action (Command) or return data (Query), not both. Separate methods that modify state from those that retrieve state.
Improves clarity and predictability. Easier to reason about side effects. Enables better caching and optimization.
When designing public interfaces and APIs. Use distinct methods for reading and writing.
CoC
Convention over Configuration
Provide sensible defaults and follow established conventions rather than requiring explicit configuration for common scenarios.
Reduces boilerplate and setup time. Makes projects more consistent and easier to navigate.
When designing frameworks and libraries. Establish conventions that developers can rely on.
PIE
Program to Interfaces, not Implementations
Code against abstract interfaces rather than concrete implementations. This enables loose coupling and polymorphism.
Makes code more flexible and testable. Allows swapping implementations without changing client code.
When designing dependencies and contracts. Use interfaces for external dependencies.
PoLA
Principle of Least Astonishment
Design systems so they behave as users expect. Avoid surprising behavior or unintuitive naming. Be consistent with similar components.
Reduces cognitive load and errors. Makes code more predictable and easier to use.
When designing APIs, naming conventions, and behavior. Consider developer expectations.
📝
Coding Standards
6 items
#
C# Naming Conventions
csharp
Follow PascalCase for public members and camelCase for private fields. Use clear, descriptive names that express intent.
csharp
public class OrderProcessor
{
private List _orders; // camelCase
public void ProcessOrder(Order order) { } // PascalCase
private bool ValidatePayment(Payment payment) { }
}
.NET
🐍
Python PEP 8 Style
python
Use snake_case for variables and functions, UPPER_CASE for constants. 4-space indentation. Max line length 79 chars (PEP 8) or 88 (Black).
One public class per file. Organize members: public methods, properties, private methods. Use namespaces to organize by feature or domain.
csharp
namespace Domain.Orders
{
public class Order
{
public int Id { get; set; }
public List Items { get; set; }
public decimal GetTotal() => Items.Sum(i => i.Price);
private void ValidateItems() { }
}
}
.NET
📂
Python Project Layout
text
Standard structure: src/package_name for code, tests/ for tests, setup.py/pyproject.toml for config. Use __init__.py for packages.
Use workspaces for multi-crate projects. Separate library crates from binary crates. Clear module hierarchy with mod.rs.
toml
[workspace]
members = ["crates/api", "crates/domain"]
// src/lib.rs
pub mod domain;
pub mod services;
// domain/mod.rs
pub struct Order { }
pub mod validators;
Rust
🎯
Paradigms
6 items
🏗️
Object-Oriented Programming
Organize code around objects with state and behavior. Emphasizes encapsulation, inheritance, and polymorphism. Natural for modeling real-world entities.
all
λ
Functional Programming
Treat computation as the evaluation of pure functions. Emphasizes immutability, higher-order functions, and avoiding side effects. Easier reasoning and testing.
all
⚛️
Reactive Programming
Build responsive systems using observable streams and event-driven architecture. Components react to data changes. Good for handling async operations.
all
📋
Procedural Programming
Organize code as a sequence of procedures/functions that modify state. Direct control flow. Good for straightforward, step-by-step logic.
all
📐
Declarative Programming
Specify what you want rather than how to achieve it. Let the system figure out the steps. Examples: SQL, configuration-based systems.
all
👤
Actor Model
Concurrent systems based on independent actors communicating via messages. Avoids shared state and race conditions. Excellent for distributed systems.
all
🏛️
Architectural Patterns
8 items
🎯
Clean Architecture
Concentric layers separating concerns: Entities, Use Cases, Interface Adapters, Frameworks. Dependencies point inward. Highly testable and decoupled.
Layers4
🔷
Hexagonal Architecture
Ports and Adapters. Core business logic at center with external dependencies as adapters. Enables multiple entry/exit points without changing core logic.
SynonymsPorts & Adapters
🔗
Microservices
Independently deployable services built around business capabilities. Each service has its own database. Scaled and developed independently. Increased complexity.
CommunicationAsync/REST/gRPC
📦
Modular Monolith
Single deployment unit with clear module boundaries. Modules communicate through well-defined interfaces. Balances simplicity of monolith with organization of microservices.
ComplexityMedium
🏘️
Domain-Driven Design
Align software structure with business domain. Use ubiquitous language shared between developers and domain experts. Organize around bounded contexts.
FocusBusiness Value
⚡
Event-Driven Architecture
Components communicate through events. Decoupled producers and consumers. Excellent for real-time systems and maintaining eventual consistency across services.
PatternPub/Sub
🌐
Service-Oriented Architecture
Business capabilities exposed as reusable services. Heavy use of messaging and protocols. Enterprise-level approach, often with ESB and SOAP.
ProtocolSOAP/REST
☁️
Serverless Architecture
Run code without managing servers. Scale automatically. Pay per execution. Good for event-driven workloads and variable traffic patterns.
ScalingAutomatic
🎨
Design Patterns
22 items
🔨Creational PatternsObject creation mechanisms
Singleton
Creational
Ensure a class has only one instance and provide a global point of access to it. Use for loggers, configuration managers, connection pools.
When you need exactly one instance shared globally. Be careful of threading issues.
Factory Method
Creational
Define an interface for creating objects, letting subclasses decide which class to instantiate. Reduces coupling to concrete classes.
When object creation logic is complex or depends on runtime conditions.
Abstract Factory
Creational
Provide an interface for creating families of related objects. Ensures consistency across a set of related products.
When you need to create related object families (e.g., UI elements for different themes).
Builder
Creational
Separate construction of complex objects from their representation. Build objects step by step. Improves readability for objects with many parameters.
When constructing complex objects with many optional parameters or validation requirements.
Prototype
Creational
Specify kinds of objects to create using a prototype instance, cloning it rather than creating from scratch. Efficient for expensive object creation.
When object creation is expensive or when you need deep copies.
Object Pool
Creational
Reuse objects that are expensive to create by pooling them. Acquire from pool, use, return. Reduces allocation overhead.
When object creation is expensive and instances are used briefly then released.
🏗️Structural PatternsObject composition and relationships
Adapter
Structural
Convert the interface of a class into another interface clients expect. Bridge incompatible interfaces. Also called Wrapper.
When integrating third-party libraries or legacy code with incompatible interfaces.
Decorator
Structural
Attach additional responsibilities to an object dynamically, extending functionality without modifying the object. Flexible alternative to subclassing.
When you need to add behavior to individual objects without affecting others or creating new subclasses.
Proxy
Structural
Provide a surrogate or placeholder for another object to control access to it. Can add lazy loading, logging, or access control.
When you need to control access, defer creation, or add cross-cutting concerns.
Facade
Structural
Provide a unified, simplified interface to a set of interfaces in a subsystem. Hides complexity and reduces coupling.
When you want to simplify complex subsystems or provide a simpler API.
Composite
Structural
Compose objects into tree structures representing part-whole hierarchies. Clients treat individual objects and compositions uniformly.
When building tree structures (e.g., menu systems, document hierarchies).
Bridge
Structural
Decouple an abstraction from its implementation so they can vary independently. Avoid cartesian product of abstractions × implementations.
When you have multiple dimensions of variation and want to avoid explosion of subclasses.
⚙️Behavioral PatternsObject collaboration and responsibility distribution
Strategy
Behavioral
Define a family of algorithms, encapsulate each one, and make them interchangeable. Clients can select strategies at runtime.
When you have multiple algorithms for a task and need to switch between them.
Observer
Behavioral
Define a one-to-many dependency so when one object changes state, all dependents are notified automatically. Implements publish-subscribe.
When you need loose coupling between components that must react to state changes.
Command
Behavioral
Encapsulate a request as an object, allowing you to parameterize clients with different requests, queue requests, and log/undo operations.
When you need undo/redo, queuing, or command logging.
Chain of Responsibility
Behavioral
Avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle it. Pass request along a chain.
When processing logic depends on runtime conditions or should be extensible.
Mediator
Behavioral
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly.
When multiple objects need to communicate in complex ways and you want to centralize that logic.
State
Behavioral
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
When an object's behavior depends on state and you have many conditional branches.
Template Method
Behavioral
Define the skeleton of an algorithm in a base class, letting subclasses fill in specific steps. Inverts control of algorithm steps.
When you have an algorithm with varying implementations of certain steps.
Visitor
Behavioral
Represent an operation to be performed on elements of an object structure. Lets you define new operations without changing the classes of those elements.
When you need to perform operations on complex object structures and operations change frequently.
Iterator
Behavioral
Provide a way to access elements of a collection sequentially without exposing its underlying representation.
When you need to traverse collections in various ways without exposing their internal structure.
Memento
Behavioral
Capture and externalize an object's internal state without violating encapsulation, and restore the object to this state later.
When you need to implement undo functionality or save/restore object state.
🏢
Enterprise Patterns
6 items
📦
Repository Pattern
csharp
Abstract data access logic behind a repository interface. Clients interact with repositories instead of directly accessing data. Enables switching persistence mechanisms.
csharp
public interface IOrderRepository {
Task GetByIdAsync(int id);
Task> GetAllAsync();
Task SaveAsync(Order order);
}
public class OrderRepository : IOrderRepository {
private readonly DbContext _db;
public Task GetByIdAsync(int id) => _db.Orders.FindAsync(id);
}
🔄
Unit of Work Pattern
csharp
Maintain a collection of objects affected by a business transaction and coordinates writing changes and handling concurrency. Ensures all changes are atomic.
csharp
public interface IUnitOfWork {
IOrderRepository Orders { get; }
ICustomerRepository Customers { get; }
Task SaveChangesAsync();
}
var order = await _uow.Orders.GetByIdAsync(1);
order.Status = OrderStatus.Shipped;
await _uow.SaveChangesAsync();
🎯
Specification Pattern
csharp
Encapsulate query logic in reusable specification objects. Separate complex filtering rules from repositories. Makes queries composable and testable.
csharp
public class ActiveOrdersSpec : Specification {
public ActiveOrdersSpec() {
AddCriteria(o => o.Status == OrderStatus.Active);
AddInclude(o => o.Items);
}
}
var orders = await repo.GetAsync(new ActiveOrdersSpec());
⚔️
Anti-Corruption Layer
csharp
Create a layer that translates between external system contracts and your domain model. Isolates domain from changes in external systems.
csharp
public class LegacyOrderAdapter {
public Order AdaptFromLegacy(LegacyOrderDto dto) {
return new Order {
Id = dto.OrderId,
Status = MapLegacyStatus(dto.Status),
Items = dto.Items.Select(AdaptItem).ToList()
};
}
}
📊
Read Models
Maintain denormalized, query-optimized views of data separate from write models. Each read model is optimized for specific queries. Common in CQRS.
PatternCQRS
⏰
Sagas & Process Managers
Coordinate long-running, distributed transactions across multiple services. Sagas are event-driven; Process Managers route messages. Handle compensating transactions for failures.
ScopeDistributed
💾
Data Handling
6 items
🗄️
Object-Relational Mapping (ORM)
Map objects to database tables. Handle hydration and persistence automatically. Examples: Entity Framework, SQLAlchemy, SeaORM. Trade flexibility for convenience.
Entity FrameworkSQLAlchemySeaORM
⚡
Query Builders & Micro-ORMs
csharp
Write SQL with less boilerplate through fluent APIs. Dapper, Linq2Db (C#), SQLAlchemy Core (Python), sqlx (Rust). More control than ORMs, less verbose than raw SQL.
csharp
var orders = await connection.QueryAsync(
"SELECT * FROM Orders WHERE CustomerId = @CustomerId",
new { CustomerId = 123 }
);
Dappersqlx
📜
Database Migrations
csharp
Version control your schema changes. Migrations are versioned scripts or code that evolve schema over time. Reversible and trackable. Examples: Flyway, EF Migrations, Alembic.
csharp
public class AddOrderTableMigration : Migration {
public override void Up() {
CreateTable("Orders")
.WithColumn("Id").AsInt32().PrimaryKey()
.WithColumn("CustomerId").AsInt32()
.WithColumn("Total").AsDecimal();
}
}
⚙️
Caching Strategies
Reduce database hits with in-memory or distributed caches. Cache-aside, write-through, write-behind patterns. Know cache invalidation strategies.
ComplexityHigh
📊
Read Models
Denormalized views optimized for specific queries. Kept in sync with write model via events. Critical for read-heavy workloads and analytics.
🔍
Search Indexing
Full-text search and analytics via Elasticsearch, Solr, or similar. Index documents for fast, flexible querying beyond SQL capabilities.
ToolsElasticsearch, Meilisearch
📤
CQRS & Event Sourcing
6 items
1️⃣
HTTP Request
Client sends a command or query to the API endpoint.
2️⃣
Controller/Handler
Receives request, validates input, routes to command/query handler.
3️⃣
Pipeline/Middleware
Cross-cutting concerns: logging, validation, authorization, error handling.
4️⃣
Aggregate
Processes command, validates business rules, emits domain events. Single source of truth.
5️⃣
Outbox/Event Store
Persists events transactionally. Ensures no loss. Published asynchronously via message broker.
6️⃣
Projections
Subscribe to events, build denormalized read models for fast queries.
💡Event Sourcing Example: Instead of storing final state, store sequence of events (OrderCreated, PaymentProcessed, OrderShipped). Rebuild state by replaying events.
🗄️
Database Patterns
10 items
🔗
Database per Service
Each microservice owns its database schema. Enables independent scaling and schema evolution. Requires eventual consistency across services.
ScopeMicroservices
📊
Shared Database
Multiple services share a database schema. Simpler to query across services but tight coupling. Hard to scale independently.
ScopeMonolith
👥
Multi-Tenancy
Serve multiple tenants in a single database. Shared or separate schemas. Requires careful data isolation and querying. Cost-effective but complex.
🔄
Read Replicas
Replicate data to read-only copies for scaling read workloads. Asynchronous replication. Introduces eventual consistency window.
🎯
Sharding
Partition data across multiple database instances by a shard key (e.g., customer_id). Horizontal scaling for write-heavy workloads.
➡️
CQRS Split Database
Separate read and write databases. Writes go to normalized write DB, reads from optimized read DB. Projections keep them in sync.
📡
Change Data Capture (CDC)
Capture database changes as a stream of events. Trigger downstream processes, update caches, replicate to other systems.
🗑️
Soft Deletes
Mark records as deleted with a timestamp rather than removing them. Preserves history and allows recovery. Add filter to queries.
⏰
Temporal Tables
Database-native versioning. Track row changes over time. Queries can see historical versions. Available in SQL Server, PostgreSQL.
🔒
Optimistic Concurrency
Use version numbers or timestamps instead of locks. Last writer wins after checking version hasn't changed. Good for distributed systems.
🌐
API Patterns
6 items
📝
REST (Representational State Transfer)
text
Resource-oriented APIs using HTTP verbs (GET, POST, PUT, DELETE). Stateless, cacheable, standardized. Most common pattern. Status codes indicate outcome.
text
POST /api/orders
GET /api/orders/123
PUT /api/orders/123
DELETE /api/orders/123
🔷
GraphQL
graphql
Query language for APIs. Clients request exact data needed, avoiding over-fetching. Strong typing, introspection, aggregates data from multiple sources.
graphql
query {
order(id: 123) {
id
customer { name email }
items { sku quantity }
}
}
⚡
gRPC
High-performance RPC using HTTP/2 and Protocol Buffers. Typed contracts, streaming, multiplexing. Excellent for service-to-service communication.
Protocol
📡
WebSockets & SSE
Real-time bidirectional (WebSocket) or server-to-client (SSE) communication. Avoid polling. Good for notifications and live updates.
🚀
Minimal APIs
Light-weight, convention-free API definition. Map HTTP endpoints directly to handler functions. Less ceremony than controllers. Common in .NET 6+.
.NET
🚪
API Gateway
Single entry point for clients. Routes requests, handles authentication, rate limiting, response transformation. Decouples clients from backend services.
💬
Messaging & Events
9 items
📢
Pub/Sub (Publish/Subscribe)
Publishers send messages to a topic; subscribers receive copies. Decouples producers from consumers. Examples: Azure Service Bus Topics, AWS SNS, RabbitMQ Topic Exchange.
📦
Message Queue
FIFO delivery of messages to a queue. Single consumer per message. Guarantees order and delivery. Examples: Azure Queue Storage, RabbitMQ Queues, SQS.
⚡
Event Streaming
Append-only log of events. Consumers read from any offset. Replay-able history. Examples: Kafka, Pulsar, Azure Event Hubs.
DeliveryAt-Least-Once
⚠️
Dead Letter Queue (DLQ)
Messages that fail processing multiple times are moved to a DLQ for investigation. Prevents poison pill messages from blocking queue.
👥
Competing Consumers
Multiple instances consume from same queue in parallel. Each message processed once. Scale processing by adding consumers.
🔄
Request-Reply Pattern
Sender publishes request on a queue, receiver processes and replies on reply queue. Synchronous semantics over async transport.
📎
Claim Check Pattern
Large message payload moved to blob storage; message contains reference/claim check. Reduces message size and bus load.
💃
Choreography
Services communicate directly via events. Each service knows what events trigger its actions. Distributed decision-making. Can get tangled.
🎼
Orchestration
Central orchestrator/saga manager directs the flow. Services do not know about each other. Clearer flow but central point of failure.
⚙️
Concurrency
6 items
⏳
Async/Await
csharp
Non-blocking operations that free up threads while waiting. Efficient use of thread pool. Syntactically simple with async/await keywords. Standard pattern.
csharp
public async Task GetOrderAsync(int id) {
var order = await _db.Orders.FindAsync(id);
var items = await _db.OrderItems
.Where(i => i.OrderId == id)
.ToListAsync();
return order;
}
🔒
Mutex/Lock/Semaphore
Mutual exclusion for accessing shared resources. Mutex (binary), Lock (reentrant), Semaphore (count). Risk of deadlock. Use sparingly in async code.
🚇
Channels
Thread-safe communication between concurrent tasks/goroutines. Producer-consumer pattern. Typed, built-in cancellation. Rust: mpsc channels, C#: System.Threading.Channels.
⚡
Thread Pool / Task Parallel
Automatically manage thread creation and reuse. Task Parallel Library (C#) coordinates work. Avoids manual thread creation and context switching overhead.
🎯
Single-Flight/Deduplication
Coalesce multiple identical concurrent requests into a single operation. Return same result to all requesters. Avoid thundering herd.
🦀
Rust Ownership & Borrowing
Compile-time concurrency safety. Ownership rules prevent data races. Move vs borrow semantics. No need for locks on immutable shared data.
Rust
🧪
Testing
8 items
📍
Unit Tests
Test individual functions/methods in isolation with mocks. Fast, fine-grained feedback. Cover happy paths and edge cases.
Pyramid70%
🔗
Integration Tests
Test components working together (database, external services). Use test doubles or in-memory databases. Slower but more realistic.
Pyramid20%
📋
Contract Tests
Verify API contracts between services without full E2E testing. Consumer-driven contracts. Catch integration issues early.
🎲
Property-Based Tests
Generate random inputs and verify invariants hold. Examples: QuickCheck, Hypothesis. Find edge cases you didn't think of.
📸
Snapshot Tests
Capture output (JSON, HTML) and verify against stored snapshots. Good for UI, configuration, complex data structures.
Inject small code changes and verify tests catch them. Low mutation score indicates insufficient test coverage.
🔺Testing Pyramid: 70% unit tests, 20% integration tests, 10% E2E. Many fast unit tests, fewer slow E2E tests.
❌
Error Handling
4 items
📦
Result/Either Type
rust
Return Result<T, E> or Either<L, R> instead of throwing exceptions. Explicit error handling. Composable with map/flatMap. Rust Result, Scala Either.
rust
pub fn process_order(order: Order) -> Result {
let payment = process_payment(&order)?;
let confirmation = create_confirmation(&order, &payment)?;
Ok(confirmation)
}
🏗️
Exception Hierarchy
csharp
Create domain-specific exception classes inheriting from base. Catch specific exceptions. Avoid catching generic Exception.
csharp
public class OrderException : Exception { }
public class InsufficientFundsException : OrderException { }
public class ItemOutOfStockException : OrderException { }
🔄
Retry with Backoff
csharp
Exponential or fixed backoff for transient failures. Jitter to avoid thundering herd. Max retries to avoid infinite loops. Use Polly (C#), tenacity (Python).
Prevent cascading failures by stopping requests to failing service. Open → Half-Open → Closed states. Polly, Hystrix, or cloud SDK.
🔐
Security
12 items
🔑
OAuth 2.0 & OpenID Connect
Delegate authentication to identity provider. OAuth 2.0 for authorization, OIDC adds identity. Authorization Code flow for web, PKCE for SPAs.
StandardRFC 6749
🎫
JWT + Refresh Tokens
Stateless authentication with JWTs. Short-lived access tokens + long-lived refresh tokens. No session storage needed. Verify signature server-side.
👥
RBAC & ABAC
Role-Based (RBAC) or Attribute-Based (ABAC) access control. RBAC: users have roles with permissions. ABAC: fine-grained rules on user/resource attributes.
🔓
API Key Authentication
Simple token-based auth for service-to-service or public APIs. Stateless, easy to revoke. Send in header or query. Less secure than OAuth.
✔️
Input Validation
Validate all input at API boundaries. Type, length, format, range. Use libraries like FluentValidation (C#), Pydantic (Python). Prevent injection attacks.
🛡️
Parameterized Queries
Use parameterized statements to prevent SQL injection. Never concatenate user input into SQL. All major ORMs and drivers support this.
🔒
Secrets Management
Store secrets (API keys, passwords, connection strings) in secure vaults, not code. Azure Key Vault, AWS Secrets Manager, HashiCorp Vault.
🌐
CORS (Cross-Origin Resource Sharing)
Control which origins can access API. Specify allowed origins, methods, headers. Prevents unauthorized cross-site requests.
⏱️
Rate Limiting
Limit requests per IP/user/key to prevent abuse and DoS. Use token bucket or sliding window algorithm. Return 429 Too Many Requests.
🔗
Zero Trust
Never trust, always verify. Authenticate and authorize every request/connection. Encrypt in transit and at rest. Assume breach mentality.
🔄
Idempotency
API operations should be safe to retry. Use idempotency keys to prevent duplicate processing. Critical for payment systems.
📝
Audit Logging
Log all security events: authentication, authorization, data access, changes. Immutable logs for compliance and investigation.
🔍
Observability
5 items
📋
Structured Logging
json
Log as JSON with consistent fields (timestamp, level, trace-id, user-id, message). Query and aggregate logs by field. Tools: ELK, Loki, CloudWatch.
Request flows through middleware components. Each adds behavior (logging, auth, error handling). Order matters. Use app.Use() to add custom middleware.
Fluent API for defining validation rules. Separate validators from models. Composable, reusable, testable. Integrates with Minimal APIs.
csharp
public class CreateOrderValidator : AbstractValidator {
public CreateOrderValidator() {
RuleFor(x => x.CustomerId).NotEmpty();
RuleFor(x => x.Items).NotEmpty().WithMessage("Must have items");
}
}
.NET
🗺️
AutoMapper & Mapster
Convention-based object mapping. DTO ↔ Domain models. Reduce boilerplate. Mapster is faster than AutoMapper.
.NET
⏰
Background Services
IHostedService for long-running tasks. Worker services run continuously. Scoped dependency injection for each iteration.
.NET
🎯
Vertical Slice Architecture
Organize by feature, not layer. Each feature has command, handler, validator, projections. Reduces cross-feature coupling.
Modern, fast web framework for building APIs. Automatic OpenAPI/Swagger docs. Built on Starlette and Pydantic. Type hints drive validation and docs.
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Order(BaseModel):
id: int
total: float
@app.get("/orders/{order_id}")
async def get_order(order_id: int) -> Order:
return Order(id=order_id, total=99.99)
Python
✔️
Pydantic v2
python
Data validation and parsing using Python type hints. Automatic schema generation. Serialization/deserialization. Settings management.
python
from pydantic import BaseModel, Field, validator
class Order(BaseModel):
id: int = Field(..., gt=0)
total: float = Field(..., gt=0)
@validator("total")
def validate_total(cls, v):
if v > 1000000:
raise ValueError("Total too large")
return v
Python
🗄️
SQLAlchemy 2.x
SQL toolkit and Object-Relational Mapper. Modern API with type hints. SQLAlchemy 2.0+ emphasizes async and explicit SQL.
Python
🔗
Dependency Injection
Use dataclasses/Pydantic for DI. Dependency() in FastAPI for request scope. Or use libraries like python-dependency-injector.
Python
⏳
Async Patterns
asyncio for concurrency. async/await syntax. Asyncio.gather() for concurrent tasks. Event loops and tasks. Understanding asyncio is critical.
Python
📦
Dataclasses & Protocols
dataclasses for lightweight data structures. Protocols (structural typing) for flexible interfaces. TypedDict for dict typing.
Every caching pattern you need — from cache-aside to CDN edge caching. Choose the right strategy for your read/write ratio and consistency requirements.
🔄
Cache-Aside (Lazy Loading)
Application checks the cache first. On a miss, it queries the database, then writes the result back to the cache. Most common pattern — simple, flexible, and easy to reason about.
USE WHENRead-heavy workloads
TRADE-OFFCache miss = slower first read
all
📖
Read-Through / Write-Through
Read-through: cache auto-fetches from DB on miss. Write-through: every write goes to cache AND DB synchronously. Provides strong consistency between cache and store.
USE WHENConsistency > latency
TRADE-OFFWrite latency increases
all
✍️
Write-Behind (Write-Back)
Writes go to cache immediately, then asynchronously flushed to the database in batches. Great for write-heavy workloads but introduces durability risk if cache crashes before flush.
USE WHENWrite-heavy, can tolerate risk
TRADE-OFFData loss risk on crash
all
🔁
Refresh-Ahead & Cache Warming
Refresh-ahead: proactively refresh entries before TTL expiry based on access patterns. Cache warming: pre-populate cache on startup or deploy to avoid cold-start stampede.
TTL: automatic time-based expiration. Eviction policies: LRU (Least Recently Used), LFU (Least Frequently Used), FIFO, MRU. Choose based on access patterns and memory constraints.
LRUBest general-purpose
LFUBest for hot-spot workloads
all
🏗️
Distributed Cache
csharp
Redis Cluster, Hazelcast, Memcached — shared cache across all application nodes. Consistent hashing for key distribution. Replication for HA. Watch for thundering herd on eviction.
csharp
// Redis cluster example
var cache = ConnectionMultiplexer.Connect("redis-cluster:6379");
var db = cache.GetDatabase();
await db.StringSetAsync("order:123", json, TimeSpan.FromMinutes(15));
all
💥
Cache Invalidation
The hardest problem. Strategies: manual purge, event-driven invalidation (publish on write), surrogate-key / tag-based (Fastly, Varnish), versioned keys. Never rely on TTL alone for critical data.
all
📊
Application-Level & DB Query Cache
python
In-process memoization (dictionary, Caffeine, functools.lru_cache). DB query cache: statement-level result caching. Fast but per-instance — not shared across nodes.
Varnish, Nginx, HAProxy — cache HTTP responses at the proxy layer before hitting your app. VCL rules for fine-grained control. Combine with CDN for multi-tier caching.
all
🌐
Distributed Systems
10 items
Core distributed systems concepts — consistency models, consensus, coordination, and the fundamental trade-offs (CAP, PACELC).
🔒
Strong vs Eventual Consistency
Strong (linearizability): every read sees the most recent write. Eventual: temporary divergence allowed, converges over time. BASE (Basically Available, Soft-state, Eventually consistent) is the alternative to ACID.
STRONGBanking, inventory
EVENTUALSocial feeds, analytics
all
⚖️
ACID vs BASE
ACID: Atomicity, Consistency, Isolation, Durability — single DB transactions. BASE: Basically Available, Soft-state, Eventually consistent — distributed systems trade-off. Choose based on business requirements.
all
🔐
Distributed Locks
Redis Redlock, ZooKeeper, etcd — lease-based locks across nodes. Fencing tokens to prevent stale lock holders. Always set TTL to avoid deadlocks. Be cautious — distributed locking is notoriously hard.
all
👑
Leader Election
Etcd, Consul, Kubernetes leases — one node elected leader for coordination. Raft consensus algorithm underneath. Watch for split-brain. Use lease renewal with heartbeats.
all
🤝
Consensus Algorithms
Raft: understandable leader-based consensus. Paxos: theoretical foundation. ZAB (ZooKeeper Atomic Broadcast). All solve the problem of agreeing on a single value across unreliable nodes.
all
📍
Service Discovery
Consul, Eureka, Kubernetes DNS — how services find each other. Client-side vs server-side discovery. Health-check integrated. DNS-based (simple) vs API-based (richer metadata).
all
🔀
Two-Phase Commit (2PC)
Distributed transaction coordinator. Phase 1: prepare (all participants vote). Phase 2: commit/abort. Blocking protocol — coordinator failure blocks all participants. Use Saga pattern instead where possible.
all
📊
Isolation Levels
Read Uncommitted → Read Committed → Repeatable Read → Serializable. Higher isolation = fewer anomalies but more contention. Snapshot isolation (MVCC) is the sweet spot for most workloads.
all
🔗
CRDTs
Conflict-free Replicated Data Types — data structures that automatically merge concurrent updates without coordination. G-Counter, PN-Counter, LWW-Register, OR-Set. Used in collaborative editing and offline-first apps.
all
⏱️
Causal & Bounded Staleness
Causal consistency: respects happens-before relationships — if A caused B, everyone sees A before B. Bounded staleness: reads lag by at most N versions or T seconds. Cosmos DB offers 5 consistency levels.
all
🛡
Resilience Patterns
8 items
Build systems that survive failure. Bulkheads, timeouts, fallbacks, graceful degradation, and chaos engineering.
⏱️
Timeout & Deadline Propagation
csharp
Set request, connection, and per-operation timeouts. Propagate deadlines across service calls so downstream services know the remaining budget. Without timeouts, one slow service cascades to all callers.
csharp
var policy = Policy.TimeoutAsync(
TimeSpan.FromSeconds(5),
TimeoutStrategy.Pessimistic);
all
🧱
Bulkhead
Isolate resources (thread pools, connection pools, semaphores) per dependency so a failure in one doesn't exhaust resources needed by others. Named after ship bulkheads that contain flooding.
all
🔄
Fallback & Graceful Degradation
When a dependency fails: return cached data, a default value, or a degraded response. Disable non-critical features under stress. The user gets a partial experience rather than an error.
all
🛑
Graceful Shutdown
csharp
On SIGTERM: stop accepting new requests, drain in-flight requests, close connections, flush logs. Kubernetes gives 30s by default. Use preStop hooks for zero-downtime deployments.
csharp
app.Lifetime.ApplicationStopping.Register(() =>
{
Log.Information("Shutting down...");
// Drain in-flight work
});
all
🐒
Chaos Engineering
Intentionally inject failures to discover weaknesses. Tools: Gremlin, Chaos Mesh, Litmus. Start small — latency injection, then pod kills, then network partitions. Run in staging first, then production.
all
🔃
Failover & Self-Healing
Active-passive: standby takes over on failure. Active-active: load shared, automatic redistribution. Kubernetes reconciliation: desired state vs actual state, auto-restart on probe failure.
all
💾
Backup & Point-in-Time Recovery
Automated backups with defined RPO (Recovery Point Objective). Cross-region replication for DR. Test restores regularly — an untested backup is not a backup.
all
🚀
Startup Probe
Kubernetes startup probe: delays liveness/readiness checks for slow-starting services (JVM warm-up, large model loading). Prevents premature pod kills during initialization.
all
🚀
Scalability Patterns
8 items
Horizontal and vertical scaling, load balancing algorithms, CDN integration, and performance optimization at the infrastructure level.
↔️
Horizontal vs Vertical Scaling
Horizontal (scale out): add more nodes — requires stateless design and load balancing. Vertical (scale up): bigger machine — simpler but has ceiling. Horizontal is the cloud-native default.
HORIZONTALCloud-native, unlimited
VERTICALSimple, has ceiling
all
⚖️
Load Balancing Algorithms
Round-robin: simple rotation. Least-connections: route to least-busy. IP-hash: sticky by source. Consistent hashing: minimal redistribution on node change. L4 (TCP) vs L7 (HTTP) load balancing.
all
📈
Auto-Scaling
yaml
Kubernetes HPA (Horizontal Pod Autoscaler): scale on CPU/memory/custom metrics. Cluster autoscaler: add/remove nodes. Schedule-based: pre-scale for known traffic patterns.
Global Server Load Balancing: DNS-based geographic routing to nearest datacenter. CDN: edge-cache static assets and API responses at 200+ PoPs worldwide. Together they minimize latency globally.
all
🗜️
Response Compression
Gzip: universally supported, good compression. Brotli: 15-25% smaller than gzip for text. Enable at reverse proxy or application level. Use for HTML, JSON, CSS, JS — skip for already-compressed formats.
all
🔌
HTTP/2 & HTTP/3
HTTP/2: multiplexing (multiple streams over one connection), header compression, server push. HTTP/3: built on QUIC (UDP), zero round-trip connection setup, better on lossy networks.
all
🧠
Memoization & Object Pooling
Memoization: cache function results in-process. Object pooling: reuse expensive objects (threads, DB connections, HTTP clients). Both reduce allocation overhead and GC pressure.
Object storage, file uploads, streaming, pre-signed URLs, and handling large files in production systems.
☁️
Object Storage (S3/GCS/Blob)
csharp
Store files as objects with metadata. Pre-signed URLs for secure direct upload/download. Multipart upload for large files. Lifecycle policies for archival. Event triggers on upload.
csharp
var request = new GetPreSignedUrlRequest
{
BucketName = "my-bucket",
Key = "uploads/report.pdf",
Expires = DateTime.UtcNow.AddMinutes(15),
};
all
📤
Chunked & Resumable Upload
Split large files into chunks, upload in parallel, resume on failure. S3 multipart upload, tus protocol. Essential for large files over unreliable connections. Track upload progress.
all
🌊
Streaming File Processing
python
Process files without loading entirely into memory. Use streams for CSV parsing, image transformation, compression. Prevents OOM on large files. Node.js streams, Python generators, .NET pipelines.
python
import csv
import io
def process_large_csv(file_stream):
reader = csv.reader(io.TextIOWrapper(file_stream))
for row in reader:
yield transform(row) # Stream, never buffer all
all
🖼️
Image & Document Processing
Thumbnails: Sharp (Node), Pillow (Python), ImageSharp (.NET). PDF extraction, OCR (Tesseract), metadata stripping. Always process async — offload to background jobs or Lambda.
all
🛡️
Virus Scanning
ClamAV: open-source antivirus scanning. Run async — upload → scan queue → move to permanent storage on clean. Quarantine infected files. Never serve unscanned user uploads.
all
💽
Block & Network Storage
Block storage (EBS, persistent volumes): for database backing. Network file systems (NFS, EFS): shared access across nodes. Content-addressable storage (CAS): deduplication via content hashing.
all
🔗
Protocols & Serialization
6 items
Communication protocols and data serialization formats — from HTTP to binary formats, from JSON to Protocol Buffers.
🌐
HTTP Evolution (1.1 / 2 / 3)
HTTP/1.1: persistent connections, chunked encoding. HTTP/2: binary framing, multiplexing, header compression. HTTP/3: QUIC (UDP), zero-RTT handshake. Each version improves latency and throughput.
all
📬
AMQP & MQTT
AMQP (RabbitMQ): reliable enterprise messaging with exchanges, queues, and bindings. MQTT: lightweight IoT pub/sub with QoS levels (0: at most once, 1: at least once, 2: exactly once).
all
⚡
Protocol Buffers
protobuf
Google's binary serialization format. IDL schema → code generation. 3-10x smaller than JSON. Schema evolution with field numbers. Required for gRPC. Language-neutral.
Avro: schema-embedded binary (Kafka, Hadoop). MessagePack: binary JSON, compact and fast. BSON: MongoDB native format — superset of JSON with types. Choose based on ecosystem and schema needs.
all
📝
JSON / XML
JSON: human-readable, universally supported, schema-optional (JSON Schema). XML: verbose but powerful — XSD validation, XSLT transformation, namespaces. JSON dominates modern APIs; XML persists in enterprise.
all
🔧
Thrift & FlatBuffers
Apache Thrift: Facebook's cross-language RPC + serialization framework. FlatBuffers: zero-copy deserialization — read data directly from buffer without unpacking. Used in games and embedded systems.
Entire application deployed as a single unit. Simple to develop, test, deploy. Works well for small teams. Scaling means replicating the whole app. Consider modular monolith before microservices.
PROSSimple, fast to start
CONSHard to scale independently
all
🧱
Cell-Based Architecture
Partition the system into self-contained cells — each cell is a complete, independent deployment unit with its own data and compute. Failure in one cell cannot cascade to others. Used at AWS, Azure.
all
💾
Space-Based Architecture
Eliminate the database bottleneck using an in-memory data grid (Hazelcast, Apache Ignite). All processing happens in-memory, data replicated across nodes. Database is async write-behind. Ideal for extreme throughput.
all
🔗
Pipeline Architecture
Data flows through sequential processing stages (pipes and filters). Each stage transforms data and passes it to the next. Unix philosophy. Used in ETL, CI/CD, and stream processing. Composable and testable.
all
🏎️
Sidecar Pattern
Deploy auxiliary functionality (logging, auth, config) as a separate process alongside the main app. Share lifecycle and network. Foundation of service mesh (Envoy, Linkerd proxy). Language-agnostic cross-cutting concerns.
all
📱
BFF — Backend for Frontend
typescript
Dedicated backend per client type (web, mobile, IoT). Each BFF aggregates and tailors API responses to its client's needs. Avoids one-size-fits-all APIs. Team ownership aligned to frontend teams.
typescript
// Mobile BFF — lightweight payloads
app.get("/api/mobile/dashboard", async (req, res) => {
const [user, stats] = await Promise.all([
userService.getSummary(req.userId),
statsService.getCompact(req.userId),
]);
res.json({ user, stats }); // Tailored for mobile
});
all
🌿
Strangler Fig Pattern
Incrementally migrate from monolith to microservices. Route traffic through a façade: new features go to new services, old features gradually strangled. Zero big-bang rewrite. Named after strangler fig trees.
HTTP callbacks triggered by events. Provider POSTs to subscriber's URL. Include HMAC signature for verification. Implement retry with exponential backoff. Dead-letter failed deliveries. Stripe, GitHub, Slack all use webhooks.
XML-based RPC protocol with WS-* standards (WS-Security, WS-ReliableMessaging). WSDL defines contract. Enterprise legacy — still used in banking, healthcare, government. Heavy but feature-rich (transactions, security built-in).
all
🔷
tRPC
End-to-end typesafe APIs for TypeScript monorepos. No schema definition or code generation — types flow from server to client automatically. Supports subscriptions, middleware, and batching. Perfect for Next.js full-stack apps.
all
🔗
HATEOAS
json
Hypermedia as the Engine of Application State. REST responses include links to related actions/resources. Client discovers capabilities dynamically. True REST maturity level 3. Enables self-describing APIs.
Strategies: URI path (/v2/orders), header (Accept-Version), query param (?version=2), content negotiation (Accept: application/vnd.api.v2+json). URI versioning is most common. Support N-1 versions minimum.
all
🔍
Filtering & Sorting
Query params: ?status=active&sort=-created_at. Standardize with RQL, OData, or GraphQL args. Support field selection (?fields=id,name). Prevent injection — whitelist allowed fields. Combine with pagination.
all
📖
OpenAPI / Swagger
Contract-first REST documentation standard. Define endpoints, schemas, auth in YAML/JSON. Generate client SDKs, server stubs, and interactive docs (Swagger UI, Redoc). Version your spec alongside code.
all
📨
AsyncAPI
OpenAPI equivalent for event-driven APIs. Describe message brokers, channels, messages, and schemas. Supports Kafka, AMQP, MQTT, WebSocket. Generate docs and code from spec. Essential for microservices documentation.
all
🚦
Request Throttling
Limit concurrent request processing to prevent overload. Queue-based admission control. Semaphore pattern. Distinct from rate limiting (which counts over time). Apply at API gateway or service level.
all
🧩
API Composition
Aggregate data from multiple microservices into a single response. API Gateway or BFF handles orchestration. Parallel fan-out for independent calls. Handle partial failures with fallbacks.
all
📊
GraphQL DataLoader
typescript
Batch and cache database queries within a single request to prevent N+1. Collects individual loads, deduplicates, and executes a single batch query. Essential for GraphQL resolvers. Available in all languages.
MongoDB, Cosmos DB, Couchbase — store JSON/BSON documents. Flexible schema, embedded subdocuments vs references. Good for content management, catalogs, user profiles. Horizontal scaling via sharding.
all
🔑
Key-Value Stores
Redis, DynamoDB, etcd — simple get/set by key. Sub-millisecond reads. TTL for expiration. Redis adds data structures (lists, sets, sorted sets, streams). DynamoDB adds secondary indexes.
all
📊
Wide-Column Stores
Cassandra, HBase, ScyllaDB — column families with rows and columns. Optimized for write-heavy, time-series, and IoT workloads. Linear horizontal scaling. Tunable consistency. No joins.
InfluxDB, TimescaleDB, QuestDB — optimized for timestamped data. Automatic retention policies, downsampling, continuous aggregates. Perfect for metrics, IoT, financial data.
all
🆕
NewSQL
CockroachDB, Google Spanner, TiDB, YugabyteDB — SQL interface with horizontal scaling + full ACID. Distributed transactions across regions. Best of SQL and NoSQL worlds. Higher latency than single-node.
all
⚡
Micro-ORM (Dapper)
csharp
Thin layer over raw SQL with object mapping. No change tracking, no lazy loading — just fast, explicit queries. Dapper (.NET), Knex (Node), SQLx compile-time checked queries (Rust). Choose when ORM overhead is too much.
csharp
var orders = await connection.QueryAsync(
"SELECT * FROM orders WHERE customer_id = @Id",
new { Id = customerId });
all
🔎
Query Optimization
sql
EXPLAIN/ANALYZE to understand execution plans. Covering indexes (include columns needed by query). Join strategies: nested loop, hash join, merge join. Avoid SELECT *. Use CTEs for readability.
sql
EXPLAIN ANALYZE
SELECT o.id, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'pending'
AND o.created_at > NOW() - INTERVAL '7 days';
all
👁️
Materialized Views
Precomputed query results stored as a table. Refresh strategies: on-demand, periodic, incremental. Trade storage for read speed. PostgreSQL REFRESH MATERIALIZED VIEW CONCURRENTLY. Use for dashboards and reports.
all
⚙️
Stored Procedures & Triggers
Business logic inside the database. Stored procedures: precompiled SQL routines callable from app. Triggers: auto-execute on INSERT/UPDATE/DELETE. Use sparingly — hard to test, version, and debug.
all
🔤
Full-Text Search
PostgreSQL tsvector/tsquery, Elasticsearch, Apache Lucene. Inverted index, stemming, ranking, fuzzy matching. Use Elasticsearch for advanced faceting, aggregations, and multi-language support.
Use multiple database types in one system — each optimized for its access pattern. E.g., PostgreSQL for transactions, Redis for cache, Elasticsearch for search, S3 for files. Adds operational complexity.
Parallelism via partition count. Messages with same key always go to same partition (ordering guarantee). Consumer group members each own partitions. More partitions = more parallelism but higher overhead.
Priority queues: high-priority messages processed first (weighted consumers or separate queues). Delay queues: schedule message delivery for future time. Use for scheduled emails, retry delays, SLA-based processing.
all
✅
At-Least-Once & Exactly-Once Delivery
At-least-once: broker retries until ACK — consumer must be idempotent. Exactly-once: Transactional Outbox pattern + idempotent consumer with dedup key. True exactly-once is expensive; most systems use at-least-once + idempotency.
AT-LEAST-ONCESimple, needs idempotency
EXACTLY-ONCEComplex, Outbox + dedup
all
🚰
Back-Pressure
Flow control when producers outpace consumers. Strategies: block producer, drop messages, buffer with limit, signal consumer capacity. Reactive Streams spec defines back-pressure protocol. Essential for stream processing.
all
🔒
Pessimistic Locking
sql
SELECT FOR UPDATE — acquire row-level lock before reading. Other transactions block until lock released. Prevents lost updates but reduces concurrency. Use for critical financial operations.
sql
BEGIN;
SELECT * FROM accounts
WHERE id = 123
FOR UPDATE; -- Lock this row
UPDATE accounts
SET balance = balance - 100
WHERE id = 123;
COMMIT;
all
🔮
Futures / Promises
Async result placeholders. Future (Java/Rust) / Promise (JS) / Task (.NET) — represent a value that will be available later. Composable: chain, combine, race. Foundation of non-blocking I/O.
Server stores session state (Redis, DB). Client receives HttpOnly, Secure, SameSite cookie with session ID. Stateful — server tracks active sessions. Better for server-rendered apps. Easier revocation than JWT.
all
🏢
SAML 2.0
XML-based enterprise SSO. Identity Provider (IdP) issues signed XML assertions. Service Provider (SP) validates. Used in corporate environments (Okta, Azure AD). Being replaced by OIDC for modern apps.
all
🔏
Mutual TLS (mTLS)
Both client and server present certificates. Used for service-to-service auth in zero-trust networks. Service mesh (Istio, Linkerd) automates mTLS. No passwords or tokens — identity is the certificate.
all
🔑
MFA / WebAuthn / Passkeys
TOTP (Google Authenticator), FIDO2 hardware keys (YubiKey), WebAuthn/Passkeys (biometric). Passkeys are the future — phishing-resistant, no shared secret. Support multiple second factors.
all
🔗
ReBAC / ACL
Relationship-Based Access Control. Permissions defined by relationships between users and resources. Google Zanzibar model (SpiceDB, Authzed). ACL: per-resource permission lists. More flexible than RBAC for complex domains.
all
📋
OPA / Policy Engines
Open Policy Agent: external policy evaluation using Rego DSL. Cedar (AWS): typed policy language. Decouple authorization logic from application code. Policy-as-code, versioned, testable.
all
#️⃣
Password Hashing
python
Argon2id (recommended), bcrypt, scrypt, PBKDF2. Never MD5/SHA for passwords. Argon2: memory-hard, resistant to GPU attacks. Use library defaults for cost parameters. Salt automatically included.
python
from argon2 import PasswordHasher
ph = PasswordHasher()
hash = ph.hash("user_password")
# Verify
ph.verify(hash, "user_password") # Returns True or raises
all
🔒
Encryption at Rest & in Transit
At rest: AES-256-GCM, TDE (Transparent Data Encryption), field-level encryption for PII. In transit: TLS 1.3 (mandatory), HSTS headers, certificate pinning for mobile. Encrypt everything — defense in depth.
all
🛡️
XSS Prevention
Content Security Policy (CSP) headers. Output encoding (HTML entity escaping). DOMPurify for sanitizing HTML. Avoid innerHTML. Use framework auto-escaping (React, Angular). Strict CSP eliminates most XSS vectors.
all
🔄
CSRF Protection
Synchronizer token pattern (hidden form field). SameSite=Strict cookies eliminate most CSRF. Origin/Referer header validation. Double-submit cookie pattern. Modern SPA + SameSite cookies = CSRF largely solved.
all
🔍
Dependency Scanning
Snyk, Trivy, Grype, OWASP Dependency-Check — scan dependencies for known CVEs. Run in CI pipeline, block on critical vulnerabilities. Software Bill of Materials (SBOM) for supply chain transparency.
ELK stack (Elasticsearch, Logstash, Kibana), EFK (Fluentd), Grafana Loki, Datadog, Splunk. Ship logs from all services to one place. Query across services. Retention policies for cost management.
all
🔥
Continuous Profiling
CPU and memory flame graphs in production. Parca, Pyroscope, Datadog Continuous Profiler. Low overhead (< 2%). Identify hot code paths without reproducing locally. Compare profiles across deploys.
all
🔴
RED Metrics
Rate (requests/sec), Errors (failed requests/sec), Duration (latency distribution). The go-to framework for request-driven services (APIs, web apps). Answers: "is my service healthy for users?"
all
🟡
USE Metrics
Utilization (% busy), Saturation (queue depth), Errors (error count). For resources: CPU, memory, disk, network. Answers: "is my infrastructure healthy?" Complement RED for full picture.
all
🏆
Golden Signals
Google SRE's four signals: Latency, Traffic, Errors, Saturation. Superset of RED + USE. If you can only monitor four things, monitor these. Build alerting around golden signals first.
all
🎯
SLI / SLO / SLA
SLI: measurable indicator (p99 latency, error rate). SLO: target for the SLI (99.9% availability). SLA: contractual agreement with consequences. Error budget = 100% - SLO. When budget exhausted, freeze deploys.
SLIWhat you measure
SLOWhat you aim for
all
📈
Dashboards
Grafana (open-source), Kibana, Datadog, New Relic. Layer: overview → service → instance. Use golden signals for top-level. Avoid dashboard sprawl — maintain a curated set. Include links to runbooks.
all
🤖
Synthetic Monitoring
Automated canary requests from external locations. Test critical user flows (login, checkout). Detect outages before users. Tools: Checkly, Datadog Synthetics, Pingdom. Run every 1-5 minutes.
all
👤
Real User Monitoring (RUM)
Capture real user performance data from browsers/mobile. Core Web Vitals (LCP, FID, CLS). Correlate frontend perf with backend traces. Tools: Datadog RUM, New Relic Browser, Sentry Performance.
all
❌
Error Tracking
Sentry, Rollbar, Bugsnag — aggregate exceptions across services. Group by stack trace, track regression, assign to owners. Source maps for JS. Release tracking to identify which deploy introduced errors.
all
🔬
APM (Application Performance Monitoring)
New Relic, Dynatrace, Datadog APM — end-to-end transaction tracing, auto-instrumentation, service maps, database query analysis. Correlates traces, metrics, and logs. The single-pane-of-glass for production.
all
🏷️
Correlation IDs
Unique request ID generated at the edge, propagated through all services via headers (X-Request-Id, traceparent). Enables end-to-end request tracing across logs, metrics, and traces. Non-negotiable for microservices.
all
📉
Log Sampling
Head-based: decide at request start (sample 10% of traces). Tail-based: decide after request completes (keep all errors, sample successes). Reduces cost for high-volume systems while preserving signal.
all
🧪
Extended Testing
12 items
E2E, stress/soak/spike, chaos, security, fuzzing, TDD, BDD, mocking, test data management, and service virtualization.
🔄
End-to-End Testing
Full API flows through the entire stack. Supertest (Node), Playwright (browser), RestAssured (Java). Test critical paths: signup → login → purchase → confirm. Run against staging. Keep suite small — E2E is slow.
all
💪
Stress, Soak & Spike Testing
Stress: push beyond capacity to find breaking point. Soak: run at normal load for hours — find memory leaks, connection exhaustion. Spike: sudden traffic surge — test auto-scaling and circuit breakers.
STRESSFind breaking point
SOAKFind slow leaks
all
🐒
Chaos & Security Testing
Chaos: Gremlin, Chaos Mesh, Litmus — inject failures (pod kills, network latency, disk fill). Security: OWASP ZAP (DAST), Snyk (SCA), Semgrep/CodeQL (SAST), pen-testing. Both should run in CI.
all
🎲
Fuzzing
Feed random/malformed inputs to find crashes and edge cases. AFL, libFuzzer, cargo-fuzz (Rust). Great for parsers, serializers, and input validation. Can run continuously. Found thousands of CVEs.
all
🔴
TDD (Test-Driven Development)
Red → Green → Refactor cycle. Write a failing test first, write minimal code to pass, then refactor. Forces design-for-testability. Keeps scope focused. Not just testing — it's a design technique.
all
🥒
BDD (Behavior-Driven Development)
gherkin
Cucumber, SpecFlow — Given/When/Then syntax. Executable specifications that non-technical stakeholders can read. Bridge between business requirements and test code. Use for acceptance criteria.
gherkin
Feature: Order placement
Scenario: Successful order
Given a customer with items in cart
When they submit the order
Then order status should be "confirmed"
And payment should be charged
all
🎭
Mocking & Stubbing
Mockito (Java), Sinon (JS), unittest.mock (Python), Moq (.NET). Mocks verify interactions; stubs provide canned responses. Use for unit test isolation. Don't mock what you don't own — use adapters.
all
🏭
Test Data Management
Factories (Factory Boy, Fishery), fixtures, Object Mother pattern. Generate realistic test data on demand. Avoid shared mutable test state. Use database transactions for test isolation (rollback after each test).
all
🌐
WireMock / Mountebank
Stub external HTTP services in integration tests. Record real traffic and replay. Simulate errors, latency, timeouts. WireMock (Java/standalone), Mountebank (polyglot), MSW (browser). Essential for testing third-party APIs.
all
🚢
Extended DevOps & Deployment
12 items
CI/CD, containers, Kubernetes, service mesh, IaC, artifact repos, rollback, serverless, init containers, edge computing, and environment parity.
Docker, Podman — multi-stage builds for small images, layer caching for fast builds. Distroless/scratch base images for security. Pin versions. Scan images with Trivy. Never run as root in production.
dockerfile
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build
FROM gcr.io/distroless/nodejs20
COPY --from=build /app/dist /app
CMD ["app/server.js"]
all
☸️
Kubernetes / Orchestration
EKS, GKE, AKS — container orchestration at scale. Pods, Deployments, Services, Ingress. HPA for auto-scaling. ConfigMaps + Secrets for config. Helm for packaging. Kustomize for environment overlays.
all
🕸️
Service Mesh
Istio, Linkerd — transparent mTLS, traffic management, observability via sidecar proxies. Retry, circuit breaker, canary routing at infrastructure level. Adds complexity — evaluate need carefully.
all
🏗️
Infrastructure as Code
Terraform (multi-cloud), Pulumi (real programming languages), CloudFormation/CDK (AWS). Declarative state management. Plan → Apply. State file management. Modules for reuse. Drift detection.
all
📦
Artifact Repository
Docker Hub, GitHub Container Registry, Nexus, JFrog Artifactory. Store container images, npm packages, Maven artifacts. Vulnerability scanning on push. Retention policies. Promotion between environments.
AWS SAM, Serverless Framework, Vercel, Cloudflare Workers. No server management. Pay-per-invocation. Cold start mitigation: provisioned concurrency, lean runtimes, Snap Start (Java). Best for event-driven workloads.
all
🏁
Init Containers & Cold-Start
Init containers: run setup (migrations, config fetch) before main container. Cold-start optimization: provisioned concurrency, lean runtimes, GraalVM native images, connection pooling on startup.
all
🌍
Edge Computing
Lambda@Edge, Cloudflare Workers, Deno Deploy — run code at CDN edge locations. Sub-10ms latency. Use for auth, A/B testing, personalization, geolocation routing. Limited runtime and memory.
all
🔄
Environment Parity
Dev ≈ Staging ≈ Production. Docker Compose for local dev. Same container images across environments. Infrastructure as Code ensures identical cloud resources. Feature flags instead of environment branches.
all
📡
Real-Time Techniques
5 items
SignalR, long polling, HTTP/2 server push, chunked transfer encoding, and MQTT for IoT.
📡
SignalR
csharp
ASP.NET real-time abstraction. Auto-negotiates transport: WebSocket → SSE → Long Polling. Hubs for grouping connections. Redis backplane for multi-server scale. Strongly typed hub contracts.
csharp
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
=> await Clients.All.SendAsync("ReceiveMessage", user, message);
}
.NET
🔄
Long Polling
Client sends request, server holds it open until data is available or timeout. Client immediately reconnects. Legacy real-time fallback. Higher latency and overhead than WebSocket/SSE. Still works everywhere.
all
⬇️
HTTP/2 Server Push
Server proactively sends resources before client requests them. Useful for preloading CSS/JS. Largely deprecated in favor of 103 Early Hints and preload link headers. Chrome removed support in 2022.
all
📦
Chunked Transfer Encoding
Stream large HTTP responses progressively without knowing total size upfront. Transfer-Encoding: chunked. Used for streaming APIs, server-sent data, large file downloads. Foundation for HTTP streaming.
ETL/ELT, Lambda/Kappa architectures, ESB, data lineage, real-time analytics, master-master sync, and delta sync.
🔄
ETL & ELT Pipelines
ETL: Extract → Transform → Load (Airflow, dbt, Spark). ELT: Load raw data first, transform in warehouse (Snowflake, BigQuery). ELT is modern standard — leverage warehouse compute. dbt for SQL transformations.
ETLTransform before load
ELTLoad then transform in DW
all
🔺
Lambda Architecture
Dual processing: batch layer (complete, accurate) + speed layer (fast, approximate). Serving layer merges results. Complex to maintain two codepaths. Being replaced by Kappa for many use cases.
all
🔹
Kappa Architecture
Stream-only processing. Single pipeline processes everything as a stream (Kafka as immutable log). Replay from log for reprocessing. Simpler than Lambda. Works when stream processing is sufficient.
all
🚌
ESB (Enterprise Service Bus)
Centralized integration middleware. Message routing, transformation, orchestration. Legacy pattern — replaced by API gateways and event-driven architectures. MuleSoft, IBM Integration Bus. Still in large enterprises.
all
📊
Data Versioning & Lineage
Track data transformations end-to-end. Great Expectations for data quality. Monte Carlo for data observability. Data lineage: know where data came from and how it was transformed. Essential for compliance.
all
⚡
Real-Time Analytics
ClickHouse, Apache Druid, Apache Pinot — sub-second queries on billions of rows. Materialized views for pre-aggregation. Stream ingestion from Kafka. Use for dashboards, metrics, and user-facing analytics.
all
🔄
Master-Master Sync
Bidirectional replication between databases. Both accept writes. Requires conflict resolution (last-write-wins, merge, manual). Complex — prefer single-master with read replicas when possible.
all
📡
Delta Sync
Only transfer changed data since last sync. CDC-based (Debezium), timestamp-based, or version-based. Dramatically reduces data transfer. Used in mobile offline-first apps, caching layers, and replication.
Shutdown: handle SIGTERM, stop accepting requests, drain in-flight work, close connections, flush logs. Jobs: Quartz (.NET/Java), Hangfire, APScheduler (Python), node-cron. Cron for recurring, delay queues for one-off.
all
⚙️
Configuration Management
Externalize config from code. Environment variables, Consul KV, Spring Cloud Config, AWS Parameter Store. 12-factor app principles. Config hierarchy: defaults → env file → env vars → CLI args. Never commit secrets.
all
🌍
i18n / L10n
ICU message format for pluralization and gender. React-intl, i18next, gettext. RTL layout support. Extract strings at build time. Use CLDR for locale data. Store translations in JSON/PO files.
all
🕐
Timezone & Currency Handling
typescript
Store timestamps in UTC always. Convert to user timezone for display. Use Temporal API (JS) or NodaTime (.NET). Currency: never use float — Decimal, BigDecimal, or integer cents. Locale-aware formatting.
typescript
// Store UTC, display local
const utc = new Date().toISOString();
const local = new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
dateStyle: "medium", timeStyle: "short"
}).format(new Date(utc));
all
🌱
Database Seeding
Populate database with initial/test data. Separate seed scripts for dev, staging, production. Factories for generating realistic data. Idempotent seeds (check before insert). Reset scripts for testing.
Deprecation: Sunset header, API versioning, migration guides, usage tracking before removal. Read-only mode: circuit breaker flag to disable writes during maintenance — serve reads from cache/replicas.
all
🌿
Trunk-Based Development
Short-lived feature branches (< 1 day). Merge to main frequently. Feature flags for incomplete work. No long-lived branches. CI runs on every push. Enables continuous deployment.
all
🔏
GDPR Compliance
Right to erasure (soft-delete with hard-delete schedule). Data retention policies. Consent logging. Data portability (export user data). Privacy by design. DPO notification within 72 hours of breach.
all
📐
Extended Code Quality
3 items
Mediator pattern, DTOs, and static analysis tools.
📨
Mediator (MediatR)
csharp
Decouple request senders from handlers. Central mediator dispatches commands/queries to their handlers. Foundation for CQRS. MediatR (.NET), mediatr-ts (TypeScript). Pipeline behaviors for cross-cutting concerns.
csharp
public record CreateOrderCommand(string Customer) : IRequest;
public class CreateOrderHandler : IRequestHandler
{
public async Task Handle(CreateOrderCommand cmd, CancellationToken ct)
{
var order = new Order(cmd.Customer);
await _db.SaveChangesAsync(ct);
return order.Id;
}
}
all
📦
DTO (Data Transfer Object)
Separate API shape from domain model. Map domain entities to DTOs for responses. Prevents leaking internal structure. Use AutoMapper (.NET), class-transformer (TS), or manual mapping. Different DTOs per API version.
all
🔍
Static Analysis
SonarQube, ESLint, Checkmarx, Semgrep, CodeQL. Run in CI — gate on quality thresholds. Track code smells, complexity, duplication, security vulnerabilities. Autofix where possible. Enforce team standards.
all
🚀
Extended Scalability
3 items
Sticky sessions, keep-alive connections, and lazy loading patterns.
📌
Sticky Sessions
Session affinity: route requests from the same client to the same server. Cookie-based (JSESSIONID) or IP-hash. Required for stateful servers (in-memory sessions). Avoid when possible — prefer stateless + external session store.
all
🔗
Keep-Alive Connections
Reuse TCP connections across multiple HTTP requests. Avoid handshake overhead. HTTP/1.1 Connection: keep-alive (default). Set appropriate timeout and max-requests. Connection pooling for upstream services.
all
💤
Lazy Loading
Defer initialization until first access. ORM lazy loading (load related entities on access). Module lazy loading. Reduces startup time and memory. Beware of N+1 queries with ORM lazy loading.