Episode 6 — Scaling Reliability Microservices Web3 / 6.1 — Microservice Foundations

6.1 -- Quick Revision

A compact, print-friendly cheat sheet covering all five subtopics of Microservice Foundations. Designed for last-minute review before interviews or exams.


Navigation README | Exercise Questions | Interview Questions | Quick Revision


How to Use This Material

  • Print it or keep it open on a second screen.
  • Cover the right column of each table and test yourself.
  • Review code snippets -- they are the minimum you should be able to write from memory.
  • Read through once the night before, then once more in the morning.

1. Vocabulary Table

TermDefinition
MonolithSingle codebase, single deployment, shared database
MicroserviceIndependently deployable service owning one business capability and its data
Distributed monolithSeparately deployed services that are still tightly coupled (shared DB, always deploy together)
Modular monolithSingle deployment with strict internal module boundaries
Bounded contextBoundary within which a domain model is defined and consistent (DDD)
Ubiquitous languageShared vocabulary between devs and domain experts within a bounded context
AggregateCluster of objects treated as a single unit for data changes
EntityObject with unique identity that persists over time (e.g., User)
Value ObjectObject defined by its attributes, not identity (e.g., Money, Address)
Domain EventRecord of something meaningful that happened (e.g., OrderPlaced)
SagaSequence of local transactions with compensating actions on failure
Eventual consistencyData converges across services over time, not immediately
CQRSCommand Query Responsibility Segregation -- separate read and write models
API CompositionAggregating data from multiple services via their APIs
Circuit breakerPattern that stops calling a failing service and returns a fallback
IdempotencyProcessing the same message N times produces the same result
Anti-Corruption LayerTranslation layer between an external model and your internal model
Strangler Fig PatternIncremental migration from monolith to microservices
Temporal couplingBoth services must be running at the same time for communication to work
Compensating transactionAn action that undoes a previous step in a saga

2. Monolith vs Microservices Comparison

DimensionMonolithMicroservices
DeploymentSingle artifactMany independent artifacts
DatabaseShared (one DB)Database per service
ScalingScale everythingScale individual services
TransactionsACID (easy)Eventual consistency (sagas)
Inter-module callsIn-process (ns)Network (ms, can fail)
Team couplingHigh (shared code)Low (independent repos)
TechnologyOne stackPolyglot possible
DebuggingSimple stack tracesDistributed tracing needed
Deployment riskHigh (all-or-nothing)Low (isolated blast radius)
Operational costLowHigh (N pipelines, N dashboards)
Best forSmall teams, early productsLarge teams, complex domains

3. Decision Framework

Should you use microservices? Score each factor 1-5:

Factor1-2 (Monolith)3 (Modular Monolith)4-5 (Microservices)
Team size< 88-20> 20
Deploy frequencyWeeklyDailyMultiple/day
Domain complexity1-2 domains3 domains4+ domains
Scaling varianceUniformSome hot spotsHighly variable
Uptime requirement99%99.9%99.99%
Tech diversityOne stackMinorMultiple stacks needed
Regulatory isolationNoneSomeRequired
  • 7-14: Monolith
  • 15-21: Modular monolith
  • 22-35: Microservices

Red flags for premature microservices:

  • Team < 5 engineers
  • "We might need to scale"
  • No CI/CD or monitoring infrastructure
  • Single, simple domain
  • Early-stage startup still finding product-market fit

4. DDD Basics for Service Boundaries

Domain --> Subdomains --> Bounded Contexts --> Services

E-commerce domain:
  Catalog (products, search, reviews)
  Ordering (cart, orders, order items)
  Payment (charges, refunds, invoices)
  Shipping (shipments, tracking, labels)
  Identity (users, auth, profiles)
  Notification (email, SMS, push)

Boundary Heuristics:

  1. Can it deploy independently?
  2. Can one team (2-8 people) own it?
  3. Does it map to a business capability (not a tech layer)?
  4. Is coupling to other services low?
  5. Does the data change together (high cohesion)?

Common Mistakes:

  • Splitting by CRUD operation (CreateUser, ReadUser, etc.)
  • Splitting by technical layer (Frontend Service, DB Service)
  • Sharing databases across services
  • Nano-services that always deploy together

5. Database Patterns

Database per Service

+--------+    +--------+    +---------+
| Svc A  |    | Svc B  |    | Svc C   |
+---+----+    +---+----+    +----+----+
    |             |              |
+---+----+    +---+----+    +----+----+
| DB A   |    | DB B   |    | DB C    |
+--------+    +--------+    +---------+
Rule: Services access ONLY their own DB. Cross-service = API or events.

Saga Pattern

Choreography (events, decentralised):
  OrderCreated -> InventoryReserved -> PaymentSucceeded -> OrderConfirmed
  If payment fails: PaymentFailed -> InventoryReleased -> OrderCancelled

Orchestration (central coordinator):
  Orchestrator --> reserve inventory --> charge payment --> confirm order
  On failure:  --> refund payment --> release inventory --> cancel order

Use choreography for 2-4 steps. Use orchestration for 5+ steps.

API Composition

// Aggregate data from multiple services
const [user, orders, reviews] = await Promise.all([
  axios.get(`${USER_SVC}/users/${id}`),
  axios.get(`${ORDER_SVC}/orders?userId=${id}`),
  axios.get(`${REVIEW_SVC}/reviews?userId=${id}`),
]);
res.json({ user: user.data, orders: orders.data, reviews: reviews.data });

CQRS

Writes --> Normalised DB (Postgres)
             |
          Events (OrderCreated, OrderUpdated)
             |
Reads  --> Denormalised DB (Elasticsearch, Mongo)

Use when read/write patterns differ significantly, complex queries needed, or high read-to-write ratio.


6. Communication Patterns

Quick Reference

PatternTypeUse When
REST (HTTP/JSON)SyncExternal APIs, simple service calls
gRPC (HTTP/2 + Protobuf)SyncHigh-throughput internal calls, streaming
Message Queue (RabbitMQ)AsyncTask distribution, one consumer per message
Pub/Sub (RabbitMQ/Kafka)AsyncEvent notification, many consumers per event
KafkaAsyncHigh-throughput event streaming, replay needed

Decision Tree

Caller needs result NOW?
  YES --> Sync (REST or gRPC)
    Internal + high throughput? --> gRPC
    External or simple? --> REST
  NO --> Async
    One consumer? --> Message queue
    Many consumers? --> Pub/sub

REST Resilience Essentials

// 1. Timeout (ALWAYS)
axios.get(url, { timeout: 3000 });

// 2. Retry with backoff
axiosRetry(client, {
  retries: 3,
  retryDelay: (n) => Math.pow(2, n) * 1000 // 1s, 2s, 4s
});

// 3. Circuit breaker
const breaker = new CircuitBreaker(fn, {
  errorThresholdPercentage: 50,
  resetTimeout: 10000,
});
breaker.fallback(() => cachedData);

Event Publishing (RabbitMQ)

// Publish
channel.publish('domain-events', 'order.created',
  Buffer.from(JSON.stringify(eventData)),
  { persistent: true }
);

// Subscribe
channel.consume(queue, async (msg) => {
  const event = JSON.parse(msg.content.toString());
  await processEvent(event);
  channel.ack(msg);
});

Idempotency Pattern

// Check idempotency key before processing
const existing = await db.query(
  'SELECT id FROM processed_events WHERE event_id = $1',
  [event.eventId]
);
if (existing.rows.length > 0) return; // already processed

// Process + record in same transaction
await db.query('BEGIN');
await processPayment(event);
await db.query('INSERT INTO processed_events (event_id) VALUES ($1)', [event.eventId]);
await db.query('COMMIT');

7. RabbitMQ vs Kafka

RabbitMQKafka
ModelMessage queueDistributed log
DeliveryPush to consumersConsumers pull
RetentionDeleted after ackRetained (configurable)
ReplayNoYes
ThroughputThousands/secMillions/sec
Best forTask queues, routingEvent streaming, replay

8. Common Gotchas

GotchaWhy It HurtsFix
Shared databaseHidden coupling, breaks independenceDatabase per service
No timeouts on HTTP callsOne slow service brings down the chainSet 2-3s timeouts on every call
No circuit breakerCascading failuresUse opossum or similar library
Not idempotent consumersDouble-processing on retryIdempotency key in every event
Synchronous everythingTemporal coupling, latency chainsUse async where caller does not need immediate result
Splitting too thinNano-services with high couplingMerge services that always change/deploy together
Splitting by tech layerDistributed monolithSplit by business capability
Big bang migrationHigh risk, long timelineStrangler Fig (incremental)
No distributed tracingCannot debug cross-service issuesCorrelation IDs + Jaeger/Datadog
Ignoring eventual consistencyUX surprises (order not showing immediately)Read-your-writes, optimistic UI

9. Architecture Diagram (Reference)

                    +------------------+
                    |   API Gateway /  |
                    |   Load Balancer  |
                    +--------+---------+
                             |
            +----------------+----------------+
            |                |                |
     +------+------+  +-----+-------+  +------+------+
     | User        |  | Order       |  | Catalog     |
     | Service     |  | Service     |  | Service     |
     +------+------+  +-----+-------+  +------+------+
            |                |                |
     +------+------+  +-----+-------+  +------+------+
     | Users DB    |  | Orders DB   |  | Catalog DB  |
     | (Postgres)  |  | (Postgres)  |  | (Postgres)  |
     +-------------+  +-------------+  +-------------+
            |                |                |
            +--------+-------+--------+-------+
                     |                |
              +------+------+  +------+------+
              |  Message    |  | Notification|
              |  Broker     |  | Service     |
              | (RabbitMQ)  |  +------+------+
              +-------------+         |
                                +-----+------+
                                | Payment    |
                                | Service    |
                                +-----+------+
                                      |
                                +-----+------+
                                | Payment DB |
                                | (Postgres) |
                                +------------+

10. Key Numbers to Remember

MetricGuideline
Team size for microservices15+ engineers
Timeout for service calls2-3 seconds
Circuit breaker error threshold50%
Circuit breaker reset timeout10-30 seconds
Retry attempts3 with exponential backoff
Retry delays1s, 2s, 4s (powers of 2)
Choreography saga steps2-4 (max)
Orchestration saga steps5+
Bounded context to service ratio1:1
Team size per service2-8 (two-pizza team)

11. One-Sentence Summaries

TopicOne Sentence
6.1.aA monolith is simpler but microservices offer independent deployment and scaling -- start monolith, evolve when needed.
6.1.bMicroservices are a trade-off (not an upgrade) justified by large teams, high deploy frequency, and complex domains.
6.1.cDraw service boundaries along bounded contexts using DDD -- split by business capability, not by technical layer.
6.1.dEach service owns its database; use sagas for distributed transactions and CQRS for complex read patterns.
6.1.eUse sync (REST/gRPC) when you need immediate results, async (queues/events) when you can defer processing.

Print this page. Review it. Ace the interview.

Navigation README | Exercise Questions | Interview Questions | Quick Revision