AlgoViz

Microservices or monolith

easy 28 min

A monolith is one program, built and released as a whole.

The same shop as one unit and as services

Read it, run it, change a line and run it again.

Loading editor…

In memory, so it runs here. The network, the broker and the databases are small classes that can fail on purpose.

The same in TypeScript
import { createServer } from "node:http";import { randomUUID } from "node:crypto";interface Item { productId: string; quantity: number; priceCents: number }interface Order { id: string; userId: string; items: Item[]; status: "PENDING"; totalCents: number }// The service's own database. save() stands for one local transaction: the order and its outbox row.class OrderDatabase {  readonly orders = new Map<string, Order>();  readonly outbox: { id: string; topic: string; key: string; payload: string }[] = [];  save(order: Order): void {    this.orders.set(order.id, order);    this.outbox.push({ id: randomUUID(), topic: "order-created", key: order.id, payload: JSON.stringify(order) });  }}const config = { name: "order-service", port: Number(process.env.PORT ?? 3001) };const database = new OrderDatabase();const totalCents = (items: Item[]) => items.reduce((sum, i) => sum + i.priceCents * i.quantity, 0);const server = createServer((request, response) => {  const send = (status: number, body: object) => {    response.writeHead(status, { "Content-Type": "application/json" });    response.end(JSON.stringify(body));  };  if (request.url === "/health") return send(200, { service: config.name, status: "healthy", at: new Date().toISOString() });  if (request.method !== "POST" || request.url !== "/orders") return send(404, { error: "not found" });  let text = "";  request.on("data", (chunk) => (text += chunk));  request.on("end", () => {    try {      const { userId, items } = JSON.parse(text) as { userId: string; items: Item[] };      const order: Order = { id: randomUUID(), userId, items, status: "PENDING", totalCents: totalCents(items) };      database.save(order); // a relay publishes the outbox row to the broker      send(201, { orderId: order.id, status: order.status, message: "Accepted, processing follows" });    } catch {      send(400, { error: "invalid order" });    }  });});process.on("SIGTERM", () => server.close(() => process.exit(0))); // finish open requests firstif (process.env.START) server.listen(config.port, () => console.log(`${config.name} on ${config.port}`));else {  database.save({ id: "o1", userId: "u1", items: [], status: "PENDING", totalCents: totalCents([{ productId: "p", quantity: 2, priceCents: 250 }]) });  console.log(database.orders.get("o1")?.totalCents, database.outbox.length);}
The same in Java
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.annotation.*;import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;import java.time.Instant;import java.util.*;record OrderItem(String productId, int quantity, long priceCents) {}record CreateOrderRequest(String userId, List<OrderItem> items) {}record OrderResponse(String orderId, String status, String message) {}record OrderRow(String id, String userId, List<OrderItem> items, String status, long totalCents, Instant createdAt) {}record OutboxRow(String id, String topic, String key, Object payload) {}record StockAnswer(String productId, boolean known, boolean available) {}interface OrderRepository { void save(OrderRow order); }interface OutboxRepository { void save(OutboxRow row); }interface StockClient { StockAnswer check(String productId); }@SpringBootApplicationclass OrderApplication {    public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); }}@RestController@RequestMapping("/orders")class OrderController {    private final OrderService service;    OrderController(OrderService service) { this.service = service; }    @GetMapping("/health")    Map<String, String> health() { return Map.of("service", "order-service", "status", "healthy"); }    @PostMapping    OrderResponse create(@RequestBody CreateOrderRequest request) { return service.create(request); }}@Serviceclass OrderService {    private final OrderRepository orders;    private final OutboxRepository outbox;    OrderService(OrderRepository orders, OutboxRepository outbox) { this.orders = orders; this.outbox = outbox; }    @Transactional // the order and its event commit together; a relay publishes the event    public OrderResponse create(CreateOrderRequest r) {        long total = r.items().stream().mapToLong(i -> i.priceCents() * i.quantity()).sum();        OrderRow order = new OrderRow(UUID.randomUUID().toString(), r.userId(), r.items(), "PENDING", total, Instant.now());        orders.save(order);        outbox.save(new OutboxRow(UUID.randomUUID().toString(), "order-created", order.id(), order));        return new OrderResponse(order.id(), order.status(), "Accepted, processing follows");    }}@Serviceclass StockGateway {    private final StockClient client;    StockGateway(StockClient client) { this.client = client; }    @CircuitBreaker(name = "stockService", fallbackMethod = "unknown")    public StockAnswer check(String productId) { return client.check(productId); }    // Same parameters plus the exception. It says "not known": it never invents stock.    public StockAnswer unknown(String productId, Throwable error) { return new StockAnswer(productId, false, false); }}/* application.ymlspring:  application.name: order-service  datasource.url: jdbc:postgresql://orders-db:5432/ordersresilience4j.circuitbreaker.instances.stockService:  slidingWindowSize: 10  failureRateThreshold: 50  waitDurationInOpenState: 30s*/