Skip to content

Application Layer (Microservices & Service Discovery)

Separating web layer from application layer

Separating the web layer from the application (platform) layer lets you scale and configure each independently. Adding a new API means adding application servers without necessarily adding web servers.

This follows the single responsibility principle: small, autonomous services working together. Small teams with small services can plan for rapid growth.

Workers in the application layer also enable asynchronism.

Microservices

  • A suite of independently deployable, small, modular services.
  • Each service runs its own process and communicates through a well-defined, lightweight mechanism to serve a business goal.

  • Example (Pinterest): user profile, follower, feed, search, photo upload, etc.

Service Discovery

Systems that help services find each other by tracking registered names, addresses, and ports:

  • Consul
  • etcd
  • ZooKeeper

Health checks (often via an HTTP endpoint) verify service integrity. Consul and etcd also have a built-in key-value store useful for config and shared data.

Disadvantages of an application layer

  • Loosely coupled services require a different approach than a monolith — architecturally, operationally, and in process.

  • Microservices add complexity in deployments and operations.

Key takeaways

  • A platform/application layer decouples scaling concerns and enables independently evolving services.

  • Microservices trade operational simplicity for team autonomy and independent scaling.

  • Service discovery is the glue that lets ephemeral, dynamically-scaled services locate each other.

Common Interview Questions

Design a ride-hailing service like Uber

Why it's asked here: Uber is a canonical microservices + service discovery example.

Key points to discuss:

  • Services: rider, driver, matching/dispatch, trip, pricing, location.
  • Service discovery (Consul/etcd/ZooKeeper) to find rider/driver services.
  • Async communication (queues) between services.
  • Geo-sharding of the matching service.
flowchart LR
    R[Rider] --> D[Dispatch service]
    DR[Driver] --> D
    D -->|geo-shard| G[(Geo DB)]
    SD[Service Discovery] --> D

Further reading


Application Tier Design Walkthrough

To design the application tier of a web service, start by defining what the tier does and how much load it must handle. The application tier sits between edge components such as DNS, CDN, and load balancers and the data tier such as caches, databases, and queues. Its job is to implement business logic, accept requests from clients, enforce authentication and input validation, coordinate calls to data services, and return responses. For a concrete plan, assume a consumer service with 10 million daily active users, about 50 million requests per day on average and 10,000 requests per second at peak, with a 90/10 read/write ratio. The tier must be stateless, horizontally scalable, highly available, and able to keep request latency low while preserving durability of writes via the data tier.

The high-level architecture is a horizontally scaled group of application servers behind one or more network load balancers. A layer-4 load balancer can terminate TCP/SSL and route to a layer-7 reverse proxy, or a single L7 gateway can decode HTTPS and route by path, host, or headers to the appropriate application service. The application servers themselves are organized around business capabilities rather than one monolithic process. For example, the service may contain separate user, product, order, session, and notification services. Each service runs multiple stateless instances; service discovery components track live instances and health checks remove bad instances from rotation. The request flow is: client to DNS, then to edge or CDN, then to a layer-4 load balancer, then to a layer-7 gateway, then to an application service, and finally to a cache or database before the response returns. A central session store, such as Redis, holds any session state because instances must not keep state in local memory; otherwise sticky sessions would be required and horizontal scaling would become uneven.

The data model and storage choices are driven by the access patterns that the application tier produces. Write-heavy transactional data such as orders, accounts, and payments belongs in a relational database because it requires atomicity, uniqueness, and indexed queries. High-volume, hot data such as sessions, rate-limit counters, and product cache entries belongs in Redis or Memcached because it must be read with sub-millisecond latency and can tolerate being rebuilt. Event-driven work such as email, push notifications, and image processing goes through a message queue or task queue so application servers do not block on slow external systems. Blobs and static assets are not stored by the application tier; they are placed in object storage and served through a CDN. This split keeps the tier itself small and focused on business logic, while storage engines each handle the workload they are best at.

The core mechanism that makes the application tier work is stateless request handling backed by externalized state. When a request arrives, the application parser authenticates it, validates and sanitizes input, looks up any required session data from the shared session store, executes the business operation, and writes or reads from the correct data store. The load balancer spreads requests across instances with least-connections or round-robin so no single instance becomes a bottleneck. Because the service keeps no local user state, any request can be handled by any instance; failed instances are simply removed from rotation. For asynchronous and slow work, the application tier enqueues a message rather than doing the work inline. The central idea is to keep the synchronous path as small as possible and push everything expensive or variable latency behind the tier.

For scaling and availability, the application tier uses multiple availability zones and auto-scaling. Each service registers with service discovery so the gateway can route to all healthy instances. Health checks run continuously and stop routing to an instance that is overloaded or crashed. Auto-scaling adds instances when CPU, memory, or request latency crosses a threshold and removes them when demand drops. The load balancer layer is itself duplicated because a single load balancer would be a single point of failure. The data tier uses replicas, sharding, and failover independently; the application tier must treat data services as remote and tolerate short outages through timeouts, retries, circuit breakers, and graceful degradation. Multiple instances and zones mean the tier can survive a whole server failure or an availability zone loss without user-visible downtime.

The main trade-offs are statelessness versus external state, synchronous versus asynchronous work, and monolithic simplicity versus service complexity. Stateless application servers are easy to scale and fail over but require a highly available external session store and pay a network hop for session access. Synchronous processing is simpler but increases latency and ties up application threads; async processing improves responsiveness but adds queue infrastructure and eventual consistency. Microservices let teams deploy independently and scale only the busy parts, but they introduce inter-service communication, deployment overhead, and more complex failure handling. Choosing L7 routing with deep path and header inspection gives flexibility but costs more than L4 routing. These trade-offs mean the application tier is designed not as one fixed box but as a horizontally partitioned set of stateless services that can each scale independently while sharing common edge, routing, and data infrastructure.

flowchart LR
    U[Users] --> DNS[DNS / CDN]
    DNS --> L4[Layer 4 LB]
    L4 --> L7[Layer 7 API Gateway]
    L7 --> A1[App instance 1]
    L7 --> A2[App instance 2]
    L7 --> AN[App instance N]
    A1 & A2 & AN --> SD[Service Discovery]
    A1 & A2 & AN --> R[(Redis Session / Cache)]
    A1 & A2 & AN --> DB[(Primary SQL DB)]
    DB --> RR[(Read Replicas)]
    A1 & A2 & AN --> Q[Message Queue]
    Q --> W[Workers]

Design a Ride-Hailing Service Like Uber

To size the system, assume 50 million monthly active users, about 5 million daily rides, 1 million concurrently active drivers at peak, and driver locations reported every 4 seconds. This produces roughly 250,000 location updates per second at peak, while ride requests may peak at about 20,000 requests per minute. The functional requirements are that riders can request a ride, nearby drivers can be matched, drivers can accept or decline, the trip can be tracked, pricing can be calculated, and payment can be settled. The non-functional requirements are low matching latency, high availability, durable trip and payment records, and horizontal scalability across many cities. Location data can tolerate brief staleness, while trip state, pricing, and payment require strong consistency.

The high-level architecture uses an API gateway in front of several microservices: user and driver services, a location-ingestion service, a dispatch and matching service, a trip service, a pricing service, a payment service, and a notification service. Rider and driver apps maintain persistent WebSocket or gRPC connections to a location gateway, which streams driver positions into the location service. The location service publishes updates to a geo-sharded matching layer and writes event history asynchronously. When a rider requests a ride, the dispatch service queries the geospatial index for nearby drivers, applies filtering and scoring, and sends offers to one or more drivers. Once a driver accepts, the trip service creates a trip record, owns the state machine, and notifies the pricing and payment services. Service discovery coordinates all of these stateless services, while message queues decouple notifications, analytics, and ride-event processing from the synchronous matching path.

The data model separates high-volume transient location state from transactional business records. Driver location and availability are stored in Redis with geospatial indexes, because matching needs sub-millisecond reads and writes against rapidly changing positions. The world is partitioned into geohash or H3 cells, and each geo-shard owns the current driver locations for its cells. User accounts, driver profiles, trips, transactions, and payment records live in a relational database because they require ACID semantics, uniqueness, and indexed queries. Trip history can be sharded by city or trip ID and replicated for availability. A NoSQL store such as Cassandra may keep raw location history for offline analysis, while an event log such as Kafka carries ride events, payments, and push notifications to asynchronous consumers. Redis caches hold hot data such as nearby drivers, fare estimates, and active trip state.

The core mechanism is geospatial matching against a partitioned driver index. Driver positions are continuously updated and assigned to a cell. When a rider requests a ride, the dispatch service computes the rider's cell and searches outward through neighboring cells until it finds enough candidate drivers. It scores candidates by estimated time of arrival, distance, driver rating, vehicle type, and current route, then sends an offer to the best driver or a small batch of drivers. The offer contains a short time-to-live, and the first accepted offer wins. After acceptance, the trip service creates an idempotent trip ID and advances the trip through states such as going-to-pickup, arrived, in-progress, completed, and canceled. Pricing uses time and distance estimates before the ride and final GPS points after the ride, while payment is settled through a payment provider with retries and reconciliation. The central challenge is handling millions of moving points and matching them without scanning all drivers, which is why the geospatial index is sharded by location rather than by driver identity.

Scaling and availability come from stateless services, geo-sharding, replication, and asynchronous fan-out. The API gateway, dispatch service, trip service, and pricing service are stateless and can scale horizontally behind load balancers. Matching is geo-sharded, so traffic from different cities or regions is isolated and a hot spot in one city does not degrade another. Redis clusters are sharded by region or geohash and replicated with failover; if a Redis shard fails, drivers reconnect and positions are refreshed within seconds. The relational database uses primary-replica replication and read replicas for trip and payment queries. Kafka buffers location history, ride events, and notifications, protecting downstream services from bursts. Failure handling is layered: a lost driver heartbeat removes the driver from the active index, a retried ride request is deduplicated by trip ID, and payment failures are retried or escalated without blocking trip completion.

The important trade-offs are location freshness versus consistency, in-memory matching versus durable storage, and synchronous dispatch versus asynchronous event processing. Driver locations are deliberately eventually consistent because sub-meter freshness at every moment would require synchronous replication and unacceptable latency, while trip and payment data are kept strongly consistent because they represent money and completed business transactions. Matching in memory is fast but loses recent location state during a cache failure, so the system accepts brief driver disappearance rather than writing every GPS update transactionally. Sharding by geohash keeps most matching local but creates edge cases at cell boundaries and can produce hot cells in dense areas, so cell sizes and search radii must be tuned. Finally, offering a ride to multiple drivers improves pickup speed but risks rejected offers and duplicate trips, while offering serially improves conversion precision but increases latency.

flowchart LR
    R[Rider app] -->|HTTPS/WebSocket| GW[API Gateway]
    D[Driver app] -->|location stream| LG[Location Gateway]
    GW --> US[User/Driver Service]
    LG --> LS[Location Service]
    LS --> G[(Geo-sharded Redis driver index)]
    LS --> K[Kafka location events]
    US --> DIS[Dispatch/Matching Service]
    DIS --> G
    DIS --> TR[Trip Service]
    TR --> DB[(Sharded SQL trip/payment DB)]
    TR --> PR[Pricing Service]
    TR --> PAY[Payment Service]
    TR --> K
    K --> N[Notification Worker]
    K --> A[Analytics Worker]
    N --> R
    N --> D