Skip to main content

Service Discovery System Design: Backend Architecture and Implementation

Comprehensive low-level design for a robust service discovery mechanism with registration, health checking, and client-side load balancing capabilities.

Service discovery is a critical component in modern distributed systems that enables services to dynamically locate and communicate with each other without hardcoding endpoints, requiring careful consideration of reliability, scalability, and fault tolerance in system design.

1. Problem Statement & Requirements

Clarifying questions

  1. What scale of service discovery are we targeting? Are we designing for a few hundred services or tens of thousands?
  2. What consistency model is required? Should we prioritize strong consistency, eventual consistency, or some hybrid approach?
  3. What are the key entities in the system? Is it just services and their instances, or do we need to model service dependencies, health status, metadata, etc.?
  4. What's the read/write ratio for service registration and lookup? Is it predominantly lookups or frequent registrations?
  5. What latency sensitivity is expected? Should we target sub-10ms lookups or can we tolerate higher latencies for better availability?
  6. What authentication and authorization model is required? Should services register with tokens, certificates, or just IP-based access?
  7. Are there any external integrations or dependencies? Will we integrate with service mesh, orchestration systems like Kubernetes, or external monitoring tools?

Functional requirements

  • Register and deregister services with metadata (version, health status, endpoints)
  • Discover services by name or tags
  • Retrieve service instances with their metadata and health status
  • Heartbeat mechanism to detect service liveness
  • Service instance health monitoring (auto-deregister unhealthy instances)
  • Service versioning and compatibility support
  • Support for service discovery in distributed environments (multi-region, multi-cluster)
  • Service instance filtering by tags or labels

Non-functional requirements

  • Latency targets: p50 < 5ms, p95 < 10ms, p99 < 50ms for service lookups
  • Throughput: 10,000+ service registrations/second and 50,000+ lookups/second
  • Availability: 99.9% uptime for service discovery system (99.99% for critical services)
  • Scalability: Support 100,000+ registered services and 1M+ concurrent lookups
  • Fault tolerance: System should continue operating with partial node failures

Constraints and assumptions

  • Assumption: Services can register with a simple HTTP endpoint or gRPC client
  • Constraint: Service instances must support graceful shutdown to deregister cleanly
  • Assumption: Services will use a heartbeat mechanism (e.g., every 30 seconds) to maintain liveness
  • Constraint: Service metadata should not exceed 1KB per instance
  • Assumption: The system will be deployed in a containerized environment (e.g., Kubernetes)
  • Constraint: Service discovery should support both synchronous and asynchronous lookup patterns

Out of scope

  • Integration with specific orchestration systems (e.g., Kubernetes, Consul)
  • Service mesh integration or service-to-service communication
  • Service configuration management (e.g., dynamic config updates)
  • Load balancing or routing logic (separate concern from discovery)
  • Service version migration or rollback capabilities
  • Cross-region service discovery with consistent global view (multi-region replication)
  • Service dependency graph visualization or analysis tools

2. API Design

API Style Selection

For service discovery, I'll use gRPC with Protocol Buffers for the following reasons:

  • Strong typing and automatic code generation
  • Efficient binary serialization with compression support
  • Built-in streaming capabilities for real-time updates
  • First-class support for service health checks and metadata exchange
  • Better performance characteristics than REST for internal service communication
  • Native support for bidirectional streaming which is essential for real-time service state updates

Endpoint Definitions

MethodPathDescriptionAuth
RegisterService/service.Discovery/RegisterServiceRegister a new service instance with metadataJWT
DeregisterService/service.Discovery/DeregisterServiceRemove a service instance from registryJWT
FindServices/service.Discovery/FindServicesQuery services by criteria (name, version, tags)JWT
GetService/service.Discovery/GetServiceRetrieve specific service instance detailsJWT
WatchServices/service.Discovery/WatchServicesSubscribe to real-time service state changesJWT
HealthCheck/service.Discovery/HealthCheckService health status endpointNone

Request and Response Schemas

RegisterService Request

message RegisterRequest {
  string service_id = 1;
  string service_name = 2;
  string version = 3;
  string host = 4;
  int32 port = 5;
  repeated string tags = 6;
  map<string, string> metadata = 7;
  int64 ttl_seconds = 8;
  int64 timestamp = 9;
}

RegisterService Response

message RegisterResponse {
  bool success = 1;
  string message = 2;
}

FindServices Request

message FindRequest {
  string service_name = 1;
  string version = 2;
  repeated string tags = 3;
  int32 limit = 4;
  int32 offset = 5;
}

FindServices Response

message FindResponse {
  repeated ServiceInstance services = 1;
  int32 total_count = 2;
}

ServiceInstance

message ServiceInstance {
  string service_id = 1;
  string service_name = 2;
  string version = 3;
  string host = 4;
  int32 port = 5;
  repeated string tags = 6;
  map<string, string> metadata = 7;
  int64 last_heartbeat = 8;
  int64 ttl_seconds = 9;
  ServiceStatus status = 10;
}

ServiceStatus Enum

enum ServiceStatus {
  UNKNOWN = 0;
  HEALTHY = 1;
  UNHEALTHY = 2;
  DEGRADED = 3;
}

HTTP Status Codes and Error Response

Status CodeDescription
200Success
400Bad Request - Invalid input parameters
401Unauthorized - Missing or invalid auth token
403Forbidden - Insufficient permissions
404Not Found - Service not found
429Too Many Requests - Rate limiting
500Internal Server Error - Unexpected server error

Standardized error response format:

{
  "error": {
    "code": "SERVICE_NOT_FOUND",
    "message": "Service with ID 'abc123' not found",
    "details": {
      "service_id": "abc123"
    },
    "timestamp": "2023-12-01T10:30:00Z"
  }
}

API Versioning Strategy

Version 1 (current) will be served at /v1/ prefix with gRPC endpoints under the same service namespace. Future versions will use /v2/ prefix.

Pagination Design

Using cursor-based pagination with offset field in FindRequest. This approach:

  • Is more efficient for large datasets
  • Provides consistent results even when data changes during pagination
  • Avoids issues with items being skipped or duplicated due to concurrent modifications

Authentication and Authorization

All endpoints require JWT authentication with the following scopes:

  • service:register - for RegisterService and DeregisterService
  • service:read - for FindServices and GetService
  • service:watch - for WatchServices

JWT tokens will include a claims structure:

{
  "sub": "service-instance-id",
  "aud": "service-discovery",
  "scope": ["service:register", "service:read"],
  "exp": 1672531200
}

Rate Limiting

Rate limiting will be implemented at the service level:

  • 1000 requests/minute per authenticated service instance
  • 5000 requests/minute for admin services (with appropriate scopes)
  • Implementation using Redis-based token bucket algorithm

Idempotency Design

For mutation endpoints (RegisterService, DeregisterService):

  • Use idempotency_key parameter in request
  • Store the operation result in Redis with TTL of 5 minutes
  • If same key is used, return cached result instead of reprocessing
  • For gRPC, this will be handled via a middleware interceptor that checks for idempotency keys and caches responses
// Example idempotency key handling in gRPC interceptor (Java)
public class IdempotencyInterceptor implements ServerInterceptor {
    private final RedisTemplate<String, String> redisTemplate;
    
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
            ServerCall<ReqT, RespT> call,
            Metadata headers,
            ServerCallHandler<ReqT, RespT> next) {
        
        String idempotencyKey = headers.get(Metadata.Key.of("idempotency-key", Metadata.ASCII_STRING_MARSHALLER));
        if (idempotencyKey != null) {
            String cachedResponse = redisTemplate.opsForValue().get("idempotency:" + idempotencyKey);
            if (cachedResponse != null) {
                // Return cached response
                return new ServerCall.Listener<ReqT>() {};
            }
        }
        
        return next.startCall(call, headers);
    }
}

3. Data Model Design

Entity-Relationship Diagram

erDiagram
    SERVICE {
        string id PK
        string name
        string version
        string status
        timestamp last_heartbeat
        timestamp created_at
        timestamp updated_at
    }

    SERVICE_INSTANCE {
        string id PK
        string service_id FK
        string instance_id
        string host
        int port
        string status
        timestamp last_heartbeat
        timestamp created_at
        timestamp updated_at
    }

    SERVICE_ENDPOINT {
        string id PK
        string service_id FK
        string path
        string method
        timestamp created_at
    }

    SERVICE_HEALTH {
        string id PK
        string service_instance_id FK
        string status
        int response_time_ms
        timestamp recorded_at
    }

    SERVICE <-- SERVICE_INSTANCE : "has"
    SERVICE <-- SERVICE_ENDPOINT : "has"
    SERVICE_INSTANCE <-- SERVICE_HEALTH : "reports"

Table Schema Definitions

Services Table

CREATE TABLE services (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    version VARCHAR(50),
    status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
    last_heartbeat TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_services_name ON services(name);
CREATE INDEX idx_services_status ON services(status);
CREATE INDEX idx_services_last_heartbeat ON services(last_heartbeat);

Service Instances Table

CREATE TABLE service_instances (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_id UUID NOT NULL REFERENCES services(id) ON DELETE CASCADE,
    instance_id VARCHAR(255) NOT NULL,
    host VARCHAR(255) NOT NULL,
    port INTEGER NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
    last_heartbeat TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    
    UNIQUE(service_id, instance_id)
);

CREATE INDEX idx_service_instances_service_id ON service_instances(service_id);
CREATE INDEX idx_service_instances_host_port ON service_instances(host, port);
CREATE INDEX idx_service_instances_last_heartbeat ON service_instances(last_heartbeat);

Service Endpoints Table

CREATE TABLE service_endpoints (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_id UUID NOT NULL REFERENCES services(id) ON DELETE CASCADE,
    path VARCHAR(500) NOT NULL,
    method VARCHAR(10) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_service_endpoints_service_id ON service_endpoints(service_id);
CREATE INDEX idx_service_endpoints_path_method ON service_endpoints(path, method);

Service Health Table

CREATE TABLE service_health (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_instance_id UUID NOT NULL REFERENCES service_instances(id) ON DELETE CASCADE,
    status VARCHAR(20) NOT NULL,
    response_time_ms INTEGER,
    recorded_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_service_health_instance_id ON service_health(service_instance_id);
CREATE INDEX idx_service_health_recorded_at ON service_health(recorded_at);

Primary Key Strategy

UUID is selected as the primary key strategy for all tables because:

  • Global uniqueness: Ensures no collisions across distributed systems
  • No coordination required: Services can generate IDs independently without centralized coordination
  • Auditability: Easier to trace and audit service instances across systems
  • Scalability: No contention on ID generation in high-concurrency environments

Index Design

  1. Services Table:

    • idx_services_name: For service name lookups (common query pattern)
    • idx_services_status: For filtering by health status in discovery
    • idx_services_last_heartbeat: For pruning stale services
  2. Service Instances Table:

    • idx_service_instances_service_id: For querying all instances of a service
    • idx_service_instances_host_port: For direct instance lookups by host/port
    • idx_service_instances_last_heartbeat: For pruning stale instances
  3. Service Endpoints Table:

    • idx_service_endpoints_service_id: For querying endpoints of a specific service
    • idx_service_endpoints_path_method: For fast endpoint lookups

Data Partitioning / Sharding Strategy

Partition by service name hash modulo N (e.g., 16 partitions) to achieve:

  • Even distribution: Services with similar names are colocated
  • Horizontal scaling: Can scale to 16+ shards based on load
  • Query locality: Service instance lookups are localized to specific shards

Soft Delete vs. Hard Delete Decision

Soft delete is chosen because:

  • Audit trail: Historical service instance and endpoint information must be preserved for debugging
  • Recovery capability: Services that were temporarily unavailable can be recovered without data loss
  • Compliance: Required for regulatory compliance in enterprise environments

Audit Trail Design

All changes to services and instances are tracked with:

  • created_at / updated_at: Timestamps for audit
  • status field: Service status changes are auditable
  • last_heartbeat: Heartbeat timestamp for service health monitoring

Data Archival Strategy and Retention Policy

  • Active services: Keep in primary storage with 30-day retention
  • Inactive services: Move to archival storage after 90 days of inactivity
  • Health metrics: Retain for 7 days, aggregate historical data for analytics
  • Endpoints: Keep indefinitely as they represent service contracts
// Example of soft delete pattern in Java
public class Service {
    private UUID id;
    private String name;
    private String version;
    private String status; // ACTIVE, INACTIVE, DELETED
    private boolean deleted = false;
    
    public void markDeleted() {
        this.status = "DELETED";
        this.deleted = true;
    }
    
    public boolean isDeleted() {
        return deleted;
    }
}

4. Class Design & Service Layer

classDiagram
    class ServiceRegistry {
        +registerService(Service)
        +deregisterService(String)
        +findService(String, String)
        +findAllServices()
        +heartbeat(String)
        +updateServiceMetadata(String, Map~String, String~)
    }
    
    class Service {
        -id: UUID
        -name: String
        -version: String
        -status: ServiceStatus
        -healthCheckUrl: String
        -lastHeartbeat: Instant
        -metadata: Map~String, String~
        -endpoints: List~Endpoint~
        +getId(): UUID
        +getName(): String
        +getStatus(): ServiceStatus
        +getLastHeartbeat(): Instant
        +isHealthy(): boolean
    }
    
    class Endpoint {
        -url: String
        -method: HttpMethod
        -path: String
        +getUrl(): String
        +getMethod(): HttpMethod
        +getPath(): String
    }
    
    class HealthChecker {
        +checkHealth(Service)
        +isHealthy(Service): boolean
    }
    
    class ServiceStatus {
        UNKNOWN
        HEALTHY
        UNHEALTHY
        DEGRADED
    }
    
    class ServiceDiscoveryEvent {
        -eventType: EventType
        -serviceId: UUID
        -serviceName: String
        -timestamp: Instant
    }
    
    class EventType {
        REGISTERED
        UPDATED
        UNREGISTERED
        HEARTBEAT
        HEALTH_CHECK_FAILED
    }
    
    class ServiceEventPublisher {
        +publish(ServiceDiscoveryEvent)
    }
    
    class ServiceCache {
        -cache: ConcurrentMap~UUID, Service~
        +get(String): Service
        +put(String, Service)
        +remove(String)
        +invalidateAll()
    }
    
    class ServiceCacheManager {
        +refreshCache()
        +invalidateCache(String)
        +getCacheSize(): int
    }
    
    ServiceRegistry --> Service : manages
    ServiceRegistry --> HealthChecker : uses
    ServiceRegistry --> ServiceEventPublisher : publishes
    ServiceRegistry --> ServiceCacheManager : manages
    
    HealthChecker --> Service : checks
    ServiceCacheManager --> ServiceCache : uses
    
    ServiceEventPublisher --> ServiceDiscoveryEvent : publishes
stateDiagram-v2
    [*] --> UNKNOWN
    UNKNOWN --> HEALTHY : register()
    UNKNOWN --> UNHEALTHY : heartbeat_timeout()
    HEALTHY --> DEGRADED : health_check_failed()
    HEALTHY --> UNHEALTHY : heartbeat_timeout()
    DEGRADED --> HEALTHY : health_check_passed()
    DEGRADED --> UNHEALTHY : health_check_failed()
    UNHEALTHY --> UNKNOWN : deregister()
    UNHEALTHY --> HEALTHY : heartbeat_received()

Service Layer Design

The service layer implements core business logic for service discovery with clear separation of concerns:

  1. ServiceRegistry - Main orchestrator managing service lifecycle and health monitoring
  2. HealthChecker - Dedicated component for health status validation
  3. ServiceCacheManager - Caching layer for performance optimization
  4. ServiceEventPublisher - Event-driven communication for system state changes

Business Logic Patterns

Strategy Pattern Implementation for Health Checks

public interface HealthCheckStrategy {
    boolean isHealthy(Service service);
}

@Component
public class HttpHealthCheckStrategy implements HealthCheckStrategy {
    private final RestTemplate restTemplate;
    
    @Override
    public boolean isHealthy(Service service) {
        try {
            String healthUrl = service.getHealthCheckUrl();
            ResponseEntity<String> response = restTemplate.getForEntity(
                healthUrl, String.class);
            return response.getStatusCode().is2xxSuccessful();
        } catch (Exception e) {
            return false;
        }
    }
}

@Component
public class ServiceRegistry {
    private final HealthCheckStrategy healthCheckStrategy;
    
    public boolean isServiceHealthy(Service service) {
        return healthCheckStrategy.isHealthy(service);
    }
}

Critical Path Method Implementation

@Transactional
public Service registerService(Service service) {
    // 1. Validate service registration
    if (service.getId() == null) {
        service.setId(UUID.randomUUID());
    }
    
    // 2. Check for existing registration
    Service existing = serviceCache.get(service.getId().toString());
    if (existing != null && !existing.getStatus().equals(ServiceStatus.UNHEALTHY)) {
        throw new ServiceAlreadyRegisteredException(
            "Service already registered: " + service.getId());
    }
    
    // 3. Validate service metadata
    validateServiceMetadata(service);
    
    // 4. Create or update service record
    Service registered = serviceRepository.save(service);
    
    // 5. Update cache with fresh data
    serviceCache.put(registered.getId().toString(), registered);
    
    // 6. Publish registration event
    ServiceDiscoveryEvent event = ServiceDiscoveryEvent.builder()
        .eventType(EventType.REGISTERED)
        .serviceId(registered.getId())
        .serviceName(registered.getName())
        .timestamp(Instant.now())
        .build();
    
    serviceEventPublisher.publish(event);
    
    // 7. Start health monitoring if not already running
    startHealthMonitoring(registered);
    
    return registered;
}

Transaction Boundary Design

  • Single transaction scope: Service registration, cache update, and event publishing are wrapped in a single database transaction
  • Consistency guarantee: All operations either succeed or rollback together
  • Isolation level: READ_COMMITTED to prevent dirty reads

Service Interface Contracts

public interface ServiceRegistryService {
    Service registerService(Service service);
    void deregisterService(String serviceId);
    Service findService(String name, String version);
    List<Service> findAllServices();
    void heartbeat(String serviceId);
    void updateServiceMetadata(String serviceId, Map<String, String> metadata);
}

Saga Pattern for Distributed Transactions

For multi-service registration scenarios:

@Component
public class ServiceRegistrationSaga {
    private final ServiceRegistryService serviceRegistry;
    private final EventPublisher eventPublisher;
    
    public void executeRegistrationSaga(ServiceRegistrationRequest request) {
        try {
            // Step 1: Register service in primary registry
            Service service = serviceRegistry.registerService(request.getService());
            
            // Step 2: Notify dependent services
            eventPublisher.publish(new ServiceRegisteredEvent(service));
            
            // Step 3: Update service discovery cache
            cacheManager.updateCache(service);
            
        } catch (Exception e) {
            // Rollback strategy
            serviceRegistry.deregisterService(request.getService().getId());
            throw new ServiceRegistrationFailedException("Failed to register service", e);
        }
    }
}

Domain Object Design

@Entity
@Table(name = "services")
public class Service {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;
    
    @Column(nullable = false)
    private String name;
    
    @Column
    private String version;
    
    @Enumerated(EnumType.STRING)
    private ServiceStatus status = ServiceStatus.UNKNOWN;
    
    @Column(name = "health_check_url")
    private String healthCheckUrl;
    
    @Column(name = "last_heartbeat")
    private Instant lastHeartbeat = Instant.now();
    
    @ElementCollection
    @MapKeyColumn(name = "key")
    @Column(name = "value")
    private Map<String, String> metadata = new HashMap<>();
    
    @OneToMany(mappedBy = "service", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Endpoint> endpoints = new ArrayList<>();
    
    // Getters and setters
}

public enum ServiceStatus {
    UNKNOWN, HEALTHY, UNHEALTHY, DEGRADED
}

Service Cache Implementation

@Component
public class ServiceCacheManager {
    private final ConcurrentMap<String, Service> cache = new ConcurrentHashMap<>();
    
    @Scheduled(fixedRate = 30_000) // Every 30 seconds
    public void refreshCache() {
        List<Service> allServices = serviceRepository.findAll();
        cache.clear();
        allServices.forEach(service -> 
            cache.put(service.getId().toString(), service));
    }
    
    public Service get(String serviceId) {
        return cache.get(serviceId);
    }
    
    public void put(String serviceId, Service service) {
        cache.put(serviceId, service);
    }
    
    public void invalidate(String serviceId) {
        cache.remove(serviceId);
    }
}

Event Publishing Design

@Component
public class ServiceEventPublisher {
    private final ApplicationEventPublisher eventPublisher;
    
    public void publish(ServiceDiscoveryEvent event) {
        eventPublisher.publishEvent(event);
    }
}

5. Concurrency & Thread Safety

Concurrency Model

The service discovery system will use a multi-threaded, event-driven architecture with the following components:

  • Thread pools: Dedicated thread pools for different operations (health checks, service registration, event handling)
  • Reactive programming model: Using Project Reactor or RxJava for asynchronous processing and backpressure handling
  • Non-blocking I/O: All I/O operations will be non-blocking to maximize throughput and minimize resource contention
  • Actor model pattern: For isolated state management of service instances and their health states

Race Condition Prevention Strategy

Race conditions can occur in several scenarios:

  1. Simultaneous service registration: Multiple instances registering simultaneously
  2. Concurrent health check updates: Multiple health check results arriving concurrently
  3. Service deregistration conflicts: Concurrent deregistrations and updates

Prevention mechanisms:

  • Use atomic operations for counters and version numbers
  • Implement lock-free data structures where possible (e.g., concurrent hash maps)
  • Apply optimistic locking with version checks for service entries
  • Use distributed locks (Redis-based or Zookeeper) for critical sections

Optimistic vs. Pessimistic Locking Selection

Optimistic locking is selected for the following reasons:

  • High throughput: Reduces lock contention in high-concurrency scenarios
  • Service discovery is read-heavy: Most operations are reads, with writes being infrequent
  • Graceful degradation: Failed updates can be retried rather than blocking the entire system
  • Scalability: Better horizontal scaling characteristics

Implementation approach:

public class ServiceInstance {
    private String id;
    private int version; // Used for optimistic locking
    private ServiceStatus status;
    
    public boolean updateWithVersion(int expectedVersion, ServiceStatus newStatus) {
        if (this.version == expectedVersion) {
            this.status = newStatus;
            this.version++;
            return true;
        }
        return false; // Conflict - retry needed
    }
}

Deadlock Prevention Strategy

Deadlock prevention is crucial in service discovery:

  1. Lock ordering: All operations acquire locks in a consistent order (e.g., by service name hash)
  2. Timeout-based acquisition: Implement timeouts for lock acquisition to prevent indefinite blocking
  3. Hierarchical locking: Service instances are grouped under service keys, with consistent ordering

Idempotency Implementation for Concurrent Duplicate Requests

Idempotency key strategy:

For registration and health check endpoints, we'll implement idempotency keys:

public class ServiceRegistrationRequest {
    private String serviceId;
    private String instanceId;
    private String idempotencyKey; // Unique key for deduplication
    private long timestamp;
    
    public boolean isDuplicate() {
        // Check if this exact request was already processed
        return serviceRegistry.isRequestProcessed(idempotencyKey);
    }
}

Implementation in service layer:

@Service
public class ServiceDiscoveryService {
    private final Set<String> processedRequests = new ConcurrentHashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    
    public boolean handleRegistration(ServiceRegistrationRequest request) {
        if (request.isDuplicate()) {
            return true; // Already processed
        }
        
        try {
            lock.writeLock().lock();
            if (request.isDuplicate()) {
                return true; // Double-check after lock acquisition
            }
            
            // Process registration
            processRegistration(request);
            
            // Mark as processed
            processedRequests.add(request.getIdempotencyKey());
            return true;
            
        } finally {
            lock.writeLock().unlock();
        }
    }
}

Thread Safety Patterns

Immutable objects for configuration:

public final class ServiceDiscoveryConfig {
    private final int healthCheckIntervalMs;
    private final int ttlSeconds;
    private final String serviceRegistryNamespace;
    
    // Constructor and getters only - no mutators
}

Thread-safe collections:

public class ServiceRegistry {
    private final Map<String, ServiceInstance> serviceInstances = 
        new ConcurrentHashMap<>();
    private final Map<String, List<ServiceInstance>> servicesByType = 
        new ConcurrentHashMap<>();
    
    public List<ServiceInstance> getInstances(String serviceType) {
        return Collections.unmodifiableList(servicesByType.getOrDefault(serviceType, Collections.emptyList()));
    }
}

Concurrency Control in Health Check Processing

Health check results are processed concurrently but with controlled access:

@Component
public class HealthCheckProcessor {
    private final ExecutorService healthCheckExecutor = 
        Executors.newFixedThreadPool(10, 
            ThreadFactoryBuilder.builder()
                .setNameFormat("health-check-%d")
                .build());
    
    public void processHealthCheck(String serviceId, HealthStatus status) {
        healthCheckExecutor.submit(() -> {
            try {
                // Update service instance with optimistic locking
                boolean updated = updateServiceInstanceWithRetry(serviceId, status);
                if (!updated) {
                    // Log conflict and retry logic
                    log.warn("Conflict updating health status for service {}", serviceId);
                }
            } catch (Exception e) {
                log.error("Failed to process health check for service {}", serviceId, e);
            }
        });
    }
}

Performance Considerations

  • Read-heavy operations: Use read-write locks to allow concurrent reads
  • High-frequency updates: Implement batching for health check updates to reduce lock contention
  • Memory efficiency: Use weak references for cache entries to prevent memory leaks in long-running systems

This design ensures that the service discovery system remains highly available and responsive under concurrent load while maintaining data consistency and preventing race conditions.

6. Sequence Diagrams for Key Flows

sequenceDiagram
    participant Client
    participant ServiceRegistry
    participant DiscoveryService
    participant ServiceInstance

    Client->>DiscoveryService: Register service instance
    DiscoveryService->>ServiceRegistry: Store service metadata
    ServiceRegistry-->>DiscoveryService: Acknowledge registration
    DiscoveryService-->>Client: Registration success response

    Client->>DiscoveryService: Discover service by name
    DiscoveryService->>ServiceRegistry: Query registered services
    ServiceRegistry-->>DiscoveryService: Return service instances
    DiscoveryService-->>Client: Service instance list

    Client->>DiscoveryService: Heartbeat service
    DiscoveryService->>ServiceRegistry: Update instance last seen timestamp
    ServiceRegistry-->>DiscoveryService: Acknowledge heartbeat
    DiscoveryService-->>Client: Heartbeat success response
sequenceDiagram
    participant Client
    participant ServiceRegistry
    participant DiscoveryService
    participant ServiceInstance

    Client->>DiscoveryService: Register service instance (failed registration)
    DiscoveryService->>ServiceRegistry: Attempt to store service metadata
    ServiceRegistry-->>DiscoveryService: Return error (duplicate registration)
    DiscoveryService-->>Client: Registration failure response

    Client->>DiscoveryService: Discover service by name (service not found)
    DiscoveryService->>ServiceRegistry: Query registered services
    ServiceRegistry-->>DiscoveryService: Return empty list
    DiscoveryService-->>Client: Service not found response

    Client->>DiscoveryService: Heartbeat service (instance expired)
    DiscoveryService->>ServiceRegistry: Update instance last seen timestamp
    ServiceRegistry-->>DiscoveryService: Return error (instance not found)
    DiscoveryService-->>Client: Heartbeat failure response
sequenceDiagram
    participant Client
    participant ServiceRegistry
    participant DiscoveryService
    participant ServiceInstance

    Client->>DiscoveryService: Async service registration
    DiscoveryService->>ServiceRegistry: Store service metadata (async)
    ServiceRegistry-->>DiscoveryService: Acknowledge async storage
    DiscoveryService-->>Client: Async registration response

    Client->>DiscoveryService: Async heartbeat (background)
    DiscoveryService->>ServiceRegistry: Update instance last seen timestamp (async)
    ServiceRegistry-->>DiscoveryService: Acknowledge async update
    DiscoveryService-->>Client: Async heartbeat response

    ServiceInstance->>DiscoveryService: Notify service instance removal
    DiscoveryService->>ServiceRegistry: Remove service instance from registry
    ServiceRegistry-->>DiscoveryService: Confirm removal
    DiscoveryService-->>Client: Service instance removed notification

7. Caching Design

Cache Strategy Selection

For service discovery, we'll use cache-aside pattern with write-through behavior for critical metadata updates. This approach provides the best balance between consistency and performance for a service registry system.

The cache-aside pattern is chosen because:

  1. It allows for explicit cache control at the application level
  2. Provides better error handling and fallback mechanisms
  3. Enables fine-grained cache invalidation strategies
  4. Supports multiple cache tiers (in-memory + distributed)

Cache Key Design

Cache keys will follow a structured namespace pattern:

service-discovery:{service-name}:{version}:{instance-id}

For metadata lookups:

service-discovery:metadata:{service-name}:{version}

For health check results:

service-discovery:health:{service-name}:{instance-id}

TTL Configuration

Data TypeTTLReason
Service Instance Metadata30 secondsFrequent updates, short-lived
Health Check Results10 secondsHigh frequency, low latency requirements
Service Registration60 secondsService heartbeats every 30s, safety margin
Service Catalog5 minutesStable data, infrequent changes

Cache Eviction Policy

LRU (Least Recently Used) will be the primary eviction policy with TTL fallback:

  • LRU ensures frequently accessed services remain in cache
  • TTL provides safety against stale data beyond expected lifecycles
  • Cache warming will be implemented for hot services

Cache Stampede Prevention

To prevent cache stampedes:

  1. Probabilistic Early Expiry: 20% of TTL for cache entries (e.g., 24 seconds instead of 30)
  2. Distributed Locks: For critical cache population operations using Redis distributed locks
  3. Cache Entry Validation: Check if another thread is populating the same cache entry

Distributed Cache Architecture

Redis Cluster with Sentinel will be used:

  • Cluster Mode: Horizontal scaling across multiple nodes
  • Sentinel: High availability and automatic failover
  • Sharding: Based on service name hash to distribute load
  • Replication: 3x replication for fault tolerance

Cache Invalidation Strategy

Event-driven invalidation will be implemented:

  1. Service Registration/Unregistration Events: Immediate cache invalidation
  2. Health Check Failures: Soft eviction with retry logic
  3. Manual Cache Invalidation: Admin endpoint for forced invalidation
@Component
public class ServiceDiscoveryCache {
    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper;
    
    public void invalidateServiceInstance(String serviceName, String instanceId) {
        String key = "service-discovery:" + serviceName + ":" + instanceId;
        redisTemplate.delete(key);
        
        // Invalidate metadata cache
        String metadataKey = "service-discovery:metadata:" + serviceName;
        redisTemplate.delete(metadataKey);
        
        // Publish cache invalidation event
        publishCacheInvalidationEvent(serviceName, instanceId);
    }
    
    public void invalidateServiceMetadata(String serviceName) {
        String key = "service-discovery:metadata:" + serviceName;
        redisTemplate.delete(key);
    }
    
    private void publishCacheInvalidationEvent(String serviceName, String instanceId) {
        // Publish to event bus for other services to invalidate their caches
        ServiceCacheInvalidationEvent event = new ServiceCacheInvalidationEvent(
            serviceName, instanceId, System.currentTimeMillis());
        eventPublisher.publish(event);
    }
}

Cache Warm-up Strategy

@Component
public class ServiceDiscoveryCacheWarmer {
    
    @Scheduled(fixedRate = 300000) // Every 5 minutes
    public void warmUpHotServices() {
        Set<String> hotServices = getHotServiceNames();
        
        for (String serviceName : hotServices) {
            try {
                // Warm up service metadata cache
                ServiceMetadata metadata = serviceRegistry.getMetadata(serviceName);
                String key = "service-discovery:metadata:" + serviceName;
                redisTemplate.opsForValue().set(key, metadata, 300, TimeUnit.SECONDS);
                
                // Warm up individual instances
                List<ServiceInstance> instances = serviceRegistry.getInstances(serviceName);
                for (ServiceInstance instance : instances) {
                    String instanceKey = "service-discovery:" + serviceName + ":" + instance.getId();
                    redisTemplate.opsForValue().set(instanceKey, instance, 30, TimeUnit.SECONDS);
                }
            } catch (Exception e) {
                log.warn("Failed to warm up cache for service: {}", serviceName, e);
            }
        }
    }
}

8. Repository / Data Access Layer

Repository Pattern Implementation

The repository pattern is implemented to abstract data access logic and provide a clean separation between domain objects and persistence concerns. Each entity has its own repository interface with standardized CRUD operations.

public interface ServiceInstanceRepository {
    Optional<ServiceInstance> findById(String instanceId);
    List<ServiceInstance> findByServiceName(String serviceName);
    List<ServiceInstance> findAll();
    ServiceInstance save(ServiceInstance instance);
    void delete(String instanceId);
    long countByServiceName(String serviceName);
    List<ServiceInstance> findHealthyInstances(String serviceName);
}

ORM vs Raw Query Decisions

For service discovery, we use a hybrid approach:

  • ORM: For complex queries involving joins and aggregations (e.g., service health statistics)
  • Raw Queries: For high-frequency operations like heartbeat updates and instance lookups

This approach balances developer productivity with performance requirements for critical paths.

Read vs Write Separation

We implement CQRS pattern for service discovery to optimize read-heavy workloads:

public class ServiceDiscoveryReadRepository {
    public List<ServiceInstance> findActiveInstances(String serviceName) {
        // Optimized read query for active service instances
        return entityManager.createQuery(
            "SELECT i FROM ServiceInstance i WHERE i.serviceName = :serviceName AND i.status = 'HEALTHY'", 
            ServiceInstance.class)
            .setParameter("serviceName", serviceName)
            .getResultList();
    }
}

public class ServiceDiscoveryWriteRepository {
    public void updateInstanceStatus(String instanceId, ServiceStatus status) {
        // Direct write for status updates
        entityManager.createQuery(
            "UPDATE ServiceInstance i SET i.status = :status, i.lastHeartbeat = :timestamp WHERE i.id = :id")
            .setParameter("status", status)
            .setParameter("timestamp", Instant.now())
            .setParameter("id", instanceId)
            .executeUpdate();
    }
}

Connection Pool Configuration

Connection pool is configured with:

  • Pool size: 20-50 connections based on concurrent service discovery requests
  • Timeout: 30 seconds for connection acquisition
  • Validation query: SELECT 1 to validate connections
@Configuration
public class DatabaseConfig {
    @Bean
    public HikariDataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:postgresql://localhost:5432/service_discovery");
        config.setMaximumPoolSize(50);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setValidationTimeout(5000);
        config.setLeakDetectionThreshold(60000);
        return new HikariDataSource(config);
    }
}

N+1 Query Prevention Strategy

We implement eager loading for service instance relationships and use batch operations:

@Repository
public class ServiceInstanceRepositoryImpl {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    public List<ServiceInstance> findInstancesWithHealthStats(List<String> serviceNames) {
        // Batch fetch related health statistics to prevent N+1
        String query = """
            SELECT i FROM ServiceInstance i 
            JOIN FETCH i.healthStats h 
            WHERE i.serviceName IN :serviceNames
            """;
        
        return entityManager.createQuery(query, ServiceInstance.class)
            .setParameter("serviceNames", serviceNames)
            .getResultList();
    }
    
    public void batchUpdateInstanceStatus(List<String> instanceIds, ServiceStatus status) {
        // Batch update to reduce database round trips
        String updateQuery = """
            UPDATE ServiceInstance i 
            SET i.status = :status, i.lastHeartbeat = :timestamp 
            WHERE i.id IN :instanceIds
            """;
        
        entityManager.createQuery(updateQuery)
            .setParameter("status", status)
            .setParameter("timestamp", Instant.now())
            .setParameter("instanceIds", instanceIds)
            .executeUpdate();
    }
}

Batch Operation Design

For high-volume service registration and heartbeat updates:

public class BatchServiceInstanceProcessor {
    
    public void processHeartbeatUpdates(List<HeartbeatUpdate> updates) {
        // Batch processing with transaction boundaries
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        
        transactionTemplate.execute(status -> {
            // Process in batches of 100 to avoid memory issues
            for (int i = 0; i < updates.size(); i += 100) {
                List<HeartbeatUpdate> batch = updates.subList(i, Math.min(i + 100, updates.size()));
                processBatch(batch);
            }
            return null;
        });
    }
    
    private void processBatch(List<HeartbeatUpdate> batch) {
        // Use native SQL for better performance in batch operations
        String sql = "UPDATE service_instances SET status = ?, last_heartbeat = ? WHERE id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            for (HeartbeatUpdate update : batch) {
                stmt.setString(1, update.getStatus().toString());
                stmt.setTimestamp(2, Timestamp.from(update.getTimestamp()));
                stmt.setString(3, update.getInstanceId());
                stmt.addBatch();
            }
            stmt.executeBatch();
        } catch (SQLException e) {
            throw new DataAccessException("Failed to process batch heartbeat updates", e);
        }
    }
}

9. Asynchronous Processing & Messaging

Event-driven boundaries in this feature — what triggers async vs. what stays synchronous, and why

Service discovery is fundamentally a distributed coordination problem that benefits from asynchronous processing to ensure high availability and reduce coupling between services. The key async triggers include:

  1. Service Registration Updates - When a service registers or updates its health status, this should be published asynchronously to allow immediate availability in the registry without blocking the registration process.
  2. Health Check Failures - When a service's health check fails, this should be asynchronously processed to remove it from the registry and notify dependent services.
  3. Service Decommissioning - When a service is decommissioned, this should be asynchronously processed to clean up registry entries and notify consumers.
  4. Service Metadata Changes - When service metadata (tags, version, etc.) changes, this should be asynchronously propagated to maintain consistency across the system.

All synchronous operations (like service lookup) should remain synchronous to ensure immediate response for client queries, while the coordination aspects of registration, health monitoring, and lifecycle management are handled asynchronously.

Message schema design with a sample payload (Avro / Protobuf / JSON Schema — with versioning strategy)

{
  "type": "object",
  "title": "ServiceEvent",
  "version": "1.0.0",
  "properties": {
    "eventId": {
      "type": "string",
      "description": "Unique identifier for the event"
    },
    "eventType": {
      "type": "string",
      "enum": ["SERVICE_REGISTERED", "SERVICE_HEALTH_CHECK_FAILED", "SERVICE_DECOMMISSIONED", "SERVICE_METADATA_UPDATED"]
    },
    "serviceName": {
      "type": "string",
      "description": "Name of the service"
    },
    "serviceId": {
      "type": "string",
      "description": "Unique identifier for the service instance"
    },
    "serviceAddress": {
      "type": "string",
      "description": "Network address of the service"
    },
    "servicePort": {
      "type": "integer",
      "description": "Network port of the service"
    },
    "metadata": {
      "type": "object",
      "description": "Additional metadata about the service"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp of the event"
    },
    "ttl": {
      "type": "integer",
      "description": "Time-to-live in seconds for the service registration"
    }
  },
  "required": ["eventId", "eventType", "serviceName", "serviceId", "timestamp"]
}

Versioning strategy uses semantic versioning with backward compatibility in mind. Major versions (e.g., v1, v2) are used for breaking changes, while minor versions (v1.0, v1.1) handle non-breaking additions.

Dead letter queue strategy and poison message handling

Poison messages are handled through a dead letter queue (DLQ) with a retry policy:

  1. Retry Policy: Messages are retried up to 3 times with exponential backoff (1s, 4s, 9s) before being sent to DLQ
  2. DLQ Handling: Messages in DLQ are logged with full context and manually inspected by operations team
  3. DLQ Cleanup: DLQ messages are automatically purged after 7 days to prevent indefinite accumulation
  4. Monitoring: DLQ queue size and message age are monitored with alerts for thresholds (e.g., >100 messages or >24h old)

At-least-once vs. exactly-once delivery — decision with justification for this feature

At-least-once delivery is chosen because:

  1. Idempotency in service registry: The registry operations (register, update, remove) are designed to be idempotent. Re-processing a registration event will not cause duplicate entries or inconsistencies.
  2. Simplicity: At-least-once is simpler to implement and maintain than exactly-once, which requires complex coordination protocols.
  3. Fault tolerance: If a message is lost or fails, at-least-once ensures that the registry eventually reaches consistency.
  4. Eventual consistency: Service discovery is an eventual consistency system, where temporary inconsistencies are acceptable as long as they resolve quickly.

Retry policy for consumers (max attempts, backoff formula, non-retryable error classification)

public class ServiceEventConsumer {
    private static final int MAX_RETRIES = 3;
    private static final long BASE_DELAY_MS = 1000;
    private static final double BACKOFF_MULTIPLIER = 4.0;
    
    public void consumeServiceEvent(ServiceEvent event) {
        int attempt = 0;
        while (attempt < MAX_RETRIES) {
            try {
                processEvent(event);
                return;
            } catch (RetryableException e) {
                attempt++;
                if (attempt >= MAX_RETRIES) {
                    handlePoisonMessage(event);
                    break;
                }
                long delay = (long) (BASE_DELAY_MS * Math.pow(BACKOFF_MULTIPLIER, attempt));
                Thread.sleep(delay);
            } catch (NonRetryableException e) {
                handlePoisonMessage(event);
                break;
            }
        }
    }
    
    private void processEvent(ServiceEvent event) throws RetryableException, NonRetryableException {
        // Process the service event
        switch (event.getEventType()) {
            case SERVICE_REGISTERED:
                handleServiceRegistration(event);
                break;
            case SERVICE_HEALTH_CHECK_FAILED:
                handleHealthCheckFailure(event);
                break;
            case SERVICE_DECOMMISSIONED:
                handleServiceDecommission(event);
                break;
            case SERVICE_METADATA_UPDATED:
                handleMetadataUpdate(event);
                break;
            default:
                throw new NonRetryableException("Unknown event type: " + event.getEventType());
        }
    }
    
    private void handlePoisonMessage(ServiceEvent event) {
        // Log to DLQ and alert operations
        log.error("Poison message in DLQ: {}", event);
        // Send to DLQ queue for manual inspection
    }
}

Outbox pattern for reliable event publishing — include or explicitly justify omission

Outbox pattern is omitted for this design because:

  1. Simplicity: Service discovery is a relatively simple system where the immediate consistency of events is acceptable for most use cases.
  2. Eventual consistency model: The system is designed to be eventually consistent, where temporary inconsistencies are acceptable.
  3. Synchronous registration: Service registration is handled synchronously to ensure immediate availability, which reduces the need for complex outbox patterns.
  4. Message broker reliability: Modern message brokers (e.g., Kafka, RabbitMQ) provide strong durability guarantees that make the outbox pattern less critical.

The system assumes that the message broker can reliably deliver events to consumers, and any failures in delivery are handled by the retry policy and DLQ strategy.

Sequence diagram for all async flows (Mermaid)

sequenceDiagram
    participant Service
    participant Registry
    participant MessageBroker
    participant Consumer
    
    Service->>MessageBroker: Publish SERVICE_REGISTERED event
    MessageBroker->>Consumer: Deliver event to consumer
    Consumer->>Registry: Update service registry with new service info
    Registry-->>Consumer: Acknowledge successful update
    
    Service->>MessageBroker: Publish SERVICE_HEALTH_CHECK_FAILED event
    MessageBroker->>Consumer: Deliver event to consumer
    Consumer->>Registry: Remove unhealthy service from registry
    Registry-->>Consumer: Acknowledge successful removal
    
    Service->>MessageBroker: Publish SERVICE_DECOMMISSIONED event
    MessageBroker->>Consumer: Deliver event to consumer
    Consumer->>Registry: Remove decommissioned service from registry
    Registry-->>Consumer: Acknowledge successful removal
    
    Service->>MessageBroker: Publish SERVICE_METADATA_UPDATED event
    MessageBroker->>Consumer: Deliver event to consumer
    Consumer->>Registry: Update service metadata in registry
    Registry-->>Consumer: Acknowledge successful update

10. Error Handling Design

Error Classification Hierarchy

Errors are categorized into three main types:

  1. Domain Errors - Business logic violations (e.g., service not found, invalid state)
  2. Infrastructure Errors - System-level issues (e.g., database connection failure, cache timeout)
  3. Validation Errors - Input validation failures (e.g., missing required fields, malformed data)
public abstract class ServiceDiscoveryException extends RuntimeException {
    private final String errorCode;
    private final int httpStatus;

    public ServiceDiscoveryException(String errorCode, int httpStatus, String message) {
        super(message);
        this.errorCode = errorCode;
        this.httpStatus = httpStatus;
    }

    public String getErrorCode() { return errorCode; }
    public int getHttpStatus() { return httpStatus; }
}

public class ServiceNotFoundException extends ServiceDiscoveryException {
    public ServiceNotFoundException(String serviceId) {
        super("SERVICE_NOT_FOUND", 404, "Service with ID " + serviceId + " not found");
    }
}

public class ServiceRegistrationException extends ServiceDiscoveryException {
    public ServiceRegistrationException(String message) {
        super("SERVICE_REGISTRATION_ERROR", 500, message);
    }
}

public class ServiceHealthCheckException extends ServiceDiscoveryException {
    public ServiceHealthCheckException(String message) {
        super("HEALTH_CHECK_FAILED", 503, message);
    }
}

Error Propagation Strategy

Errors are handled at the appropriate layer with specific strategies:

  1. Infrastructure errors (DB, cache) are wrapped and re-thrown to higher layers
  2. Validation errors are caught at the API boundary and converted to 400 responses
  3. Domain errors are handled at service layer and converted to appropriate HTTP status codes

Retry Strategy with Exponential Backoff and Jitter

For transient infrastructure errors, a retry mechanism is implemented:

public class RetryableServiceDiscoveryClient {
    private static final int MAX_RETRIES = 3;
    private static final long BASE_DELAY_MS = 1000;
    private static final double JITTER_FACTOR = 0.2;

    public <T> T executeWithRetry(Supplier<T> operation) {
        int attempts = 0;
        Exception lastException = null;

        while (attempts < MAX_RETRIES) {
            try {
                return operation.get();
            } catch (ServiceHealthCheckException | ServiceRegistrationException e) {
                lastException = e;
                attempts++;
                
                if (attempts >= MAX_RETRIES) {
                    throw new ServiceDiscoveryException(
                        "RETRY_EXHAUSTED", 500, 
                        "Failed after " + MAX_RETRIES + " attempts: " + e.getMessage()
                    );
                }

                long delay = (long) (BASE_DELAY_MS * Math.pow(2, attempts) 
                    * (1 + JITTER_FACTOR * (Math.random() - 0.5)));
                
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new ServiceDiscoveryException(
                        "RETRY_INTERRUPTED", 500, "Retry interrupted"
                    );
                }
            }
        }

        throw new ServiceDiscoveryException(
            "RETRY_FAILED", 500, 
            "Retry operation failed: " + lastException.getMessage()
        );
    }
}

Circuit Breaker Design

For external dependencies like database or cache, a circuit breaker is implemented:

public class CircuitBreaker {
    private final int failureThreshold;
    private final long timeoutMs;
    private final int successThreshold;

    private volatile CircuitState state = CircuitState.CLOSED;
    private volatile int failureCount = 0;
    private volatile long lastFailureTime = 0;

    public enum CircuitState {
        CLOSED, OPEN, HALF_OPEN
    }

    public boolean canExecute() {
        switch (state) {
            case CLOSED:
                return true;
            case OPEN:
                if (System.currentTimeMillis() - lastFailureTime > timeoutMs) {
                    state = CircuitState.HALF_OPEN;
                    return true;
                }
                return false;
            case HALF_OPEN:
                return true;
            default:
                return false;
        }
    }

    public void recordSuccess() {
        if (state == CircuitState.HALF_OPEN) {
            failureCount = 0;
            state = CircuitState.CLOSED;
        }
    }

    public void recordFailure() {
        lastFailureTime = System.currentTimeMillis();
        
        switch (state) {
            case CLOSED:
                failureCount++;
                if (failureCount >= failureThreshold) {
                    state = CircuitState.OPEN;
                }
                break;
            case HALF_OPEN:
                state = CircuitState.OPEN;
                failureCount = 0;
                break;
            case OPEN:
                // No change in state
                break;
        }
    }
}

Fallback Behavior Design

Fallbacks are implemented for critical operations:

public class ServiceDiscoveryService {
    private final CircuitBreaker circuitBreaker = new CircuitBreaker();
    
    public List<ServiceInstance> getServicesFallback(String serviceType) {
        // Return cached or default services if circuit is open
        return Collections.emptyList();
    }

    public ServiceInstance registerServiceFallback(ServiceRegistrationRequest request) {
        // Return default or throw exception if circuit is open
        throw new ServiceRegistrationException("Service registration failed due to system unavailability");
    }
}

Error Logging Format and Alerting Thresholds

Structured logging with required fields:

public class ServiceDiscoveryErrorLogger {
    private static final Logger logger = LoggerFactory.getLogger(ServiceDiscoveryErrorLogger.class);

    public void logError(String operation, Exception error, Map<String, Object> context) {
        Map<String, Object> logFields = new HashMap<>();
        logFields.put("timestamp", Instant.now().toString());
        logFields.put("operation", operation);
        logFields.put("error_code", error.getClass().getSimpleName());
        logFields.put("message", error.getMessage());
        logFields.put("stack_trace", error.getStackTrace().toString());
        logFields.putAll(context);

        logger.error("Service Discovery Error: {}", logFields);
    }

    public void alertOnCriticalErrors(String operation, Exception error) {
        if (isCriticalError(error)) {
            // Send to monitoring system (e.g., PagerDuty, Slack)
            logger.error("CRITICAL ERROR - Alerting: Operation={}, Error={}", operation, error.getMessage());
        }
    }

    private boolean isCriticalError(Exception error) {
        return error instanceof ServiceHealthCheckException || 
               error instanceof ServiceRegistrationException;
    }
}

Alerting Thresholds

MetricWarning LevelCritical LevelEscalation Path
Service Registration Failures>5/min>20/minOn-call SRE
Health Check Failures>3/min>15/minOn-call SRE
Cache Timeout Errors>2/min>10/minOn-call SRE
Circuit Breaker Tripped>5/min>20/minOn-call SRE

Error Response Format

Standardized error response:

{
  "error": {
    "code": "SERVICE_NOT_FOUND",
    "message": "Service with ID my-service not found",
    "timestamp": "2023-06-15T14:30:00Z",
    "request_id": "req-12345"
  }
}

11. Security Design

Input Validation and Sanitization Strategy

All service discovery API endpoints must validate and sanitize all inputs using a combination of:

  • Regex validation for service names, hostnames, and ports (e.g., ^[a-zA-Z0-9._-]+$ for service names)
  • Length limits (max 255 characters for identifiers)
  • Type validation using Jackson annotations or similar
  • Whitelisting approach for allowed characters and values

SQL Injection Prevention

All database queries are constructed using:

  • Prepared statements with parameterized queries (e.g., PreparedStatement ps = connection.prepareStatement("SELECT * FROM services WHERE name = ?");)
  • ORM framework (Hibernate/JPA) with proper mapping to prevent raw SQL injection
  • No dynamic query building from user input

Authentication Middleware Design

Service discovery uses a multi-layer authentication strategy:

  • API Key Authentication for service registration and health checks
  • JWT-based Bearer Token for administrative operations (service listing, metadata queries)
  • Mutual TLS between service registry and registered services for enhanced security

Authorization Enforcement

RBAC model implemented at service layer:

public class ServiceAuthorizationService {
    private final RolePermissionRepository rolePermissionRepo;
    
    public boolean canAccessService(String userId, String serviceName) {
        Set<String> userRoles = getUserRoles(userId);
        Set<String> servicePermissions = getServicePermissions(serviceName);
        
        return !Collections.disjoint(userRoles, servicePermissions);
    }
}

Sensitive Data Encryption

  • At-rest encryption: AES-256 for service metadata and registration data stored in database
  • In-transit encryption: TLS 1.3 for all service registry communications
  • Secrets storage: Encrypted secrets stored in AWS Secrets Manager with automatic rotation

PII Handling and Masking Strategy

  • Service metadata is logged with PII fields masked (e.g., IP addresses truncated to network prefix)
  • Audit logs exclude sensitive fields like passwords, tokens, or private keys
  • Logging format: {"trace_id":"1234567890","service_name":"user-service","ip_address":"10.0.0.**"}

Secrets Management

  • Vault integration for service registration tokens and TLS certificates
  • Automated rotation every 90 days with fallback mechanisms
  • Role-based access control for secret retrieval (services can only read their own tokens)

Audit Logging Design

  • Events logged: Service registration, de-registration, health check failures, permission changes
  • Log format:
{
  "timestamp": "2023-12-01T10:30:00Z",
  "event_type": "SERVICE_REGISTERED",
  "service_id": "user-service-12345",
  "user_id": "admin-user",
  "ip_address": "10.0.0.100",
  "action": "register",
  "status": "SUCCESS"
}
  • Retention policy: 90 days for audit logs with daily export to security information and event management (SIEM) system

12. Testing Strategy

Unit Testing Scope and Coverage Targets (%)

  • Service Layer: 85% code coverage with focus on business logic and edge cases
  • Repository Layer: 90% coverage, including all query paths and error conditions
  • API Controllers: 80% coverage with emphasis on request validation and response formatting
  • Domain Objects: 95% coverage for value objects and state transitions
  • Event Handlers: 85% coverage including error handling and retry scenarios

Integration Testing Strategy

  • Service Integration Tests: Use embedded database (H2/PostgreSQL) with testcontainers for real DB interactions
  • API Integration Tests: Mock external dependencies using WireMock or Mockito, test complete request-response cycles
  • Database Integration Tests: Use in-memory databases for fast execution with real schema validation
  • External Service Mocks: Implement contract testing using Pact framework for inter-service communication

Contract Testing

  • Pact Broker Integration: Maintain contract tests in Pact Broker for cross-service validation
  • Consumer-Driven Contracts: Each service publishes consumer contracts that providers must satisfy
  • Versioned Contract Testing: Ensure backward compatibility with versioned contract schemas

Performance Testing Tool and Key Scenarios

  • Tool: k6 (JavaScript-based load testing) with Grafana for visualization
  • Key Scenarios:
    • Concurrent service registration (1000 concurrent registrations)
    • Service discovery under high load (5000 concurrent lookups)
    • Failover testing (simulated service unavailability)
    • Network partition scenarios (latency simulation)
  • Metrics Tracked: p50/p95/p99 response times, error rates, throughput

Test Data Management Strategy

  • Fixtures: YAML/JSON fixtures for service metadata, health status, and registration data
  • Factories: Java-based factory classes for generating realistic test service instances
  • Seeding: Automated database seeding with pre-defined service catalog and health states
  • Test Data Isolation: Use separate test namespaces or database schemas to prevent cross-contamination

13. Observability Design

Structured Logging Schema

All logs follow a structured JSON format with the following required fields:

{
  "timestamp": "2023-10-27T14:30:00.000Z",
  "level": "INFO|WARN|ERROR",
  "service": "service-discovery",
  "trace_id": "123e4567-e89b-12d3-a456-426614174000",
  "span_id": "abcdef1234567890",
  "user_id": "user-123", 
  "entity_id": "service-abc123",
  "operation": "registerService",
  "message": "Service registered successfully",
  "error_code": "SERVICE_ALREADY_REGISTERED",
  "error_details": {
    "stack_trace": "...",
    "cause": "Duplicate service name"
  },
  "metadata": {
    "service_name": "user-service",
    "version": "v1.2.3",
    "host": "10.0.0.5:8080"
  }
}

PII masking rules:

  • User IDs and session tokens are masked in logs
  • IP addresses are truncated to network prefix (e.g., 10.0.0.x)
  • Database connection strings and secrets are completely redacted

Distributed Tracing Instrumentation

Using OpenTelemetry with custom spans:

Key Operations to Trace:

  1. serviceRegistration - Span for entire registration flow
  2. serviceHealthCheck - Health check execution span
  3. serviceLookup - Service discovery query span
  4. serviceDeregistration - Deregistration operation span

Span Attributes Captured:

  • service.name: Name of the service being operated on
  • service.version: Version string of the service
  • service.host: Host and port of the service instance
  • health.status: Health check result (healthy, unhealthy, unknown)
  • lookup.query: Service name/query used for lookup
  • lookup.results.count: Number of matching services found

Metrics Design

RED Method Metrics (Rate, Errors, Duration)

Metric NameTypeLabelsDescription
service_discovery_requests_totalCounteroperation, statusTotal count of service discovery operations
service_discovery_errors_totalCounteroperation, error_typeCount of failed operations
service_discovery_duration_secondsHistogramoperation, statusLatency distribution of operations
service_health_checks_totalCounterstatus, service_nameHealth check execution counts
service_instances_countGaugeservice_nameCurrent active service instances

Sample Histogram Bucket Configuration:

Histogram.Timer histogram = Histogram.timer("service_discovery_duration_seconds")
    .withBuckets(
        0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0
    );

Health Check Endpoint Design

Endpoints:

  • /health - Liveness check (responds if service is running)
  • /ready - Readiness check (responds if service can accept traffic)
  • /live - Same as /health
  • /startup - Startup check (validates dependencies are ready)

Response Format:

{
  "status": "healthy|unhealthy",
  "checks": {
    "database": {
      "status": "healthy",
      "details": "Connected to primary DB"
    },
    "cache": {
      "status": "healthy",
      "details": "Redis cluster connected"
    },
    "service_registry": {
      "status": "healthy",
      "details": "Service discovery is operational"
    }
  },
  "timestamp": "2023-10-27T14:30:00.000Z"
}

Alerting Thresholds

Critical Alerts (On-call escalation):

  • service_discovery_errors_total{operation="registerService"} > 5 per minute - Critical
  • service_discovery_duration_seconds{operation="lookupService"} > 500ms p99 - Critical
  • service_health_checks_total{status="unhealthy"} > 10 per minute - Critical

Warning Alerts (Monitoring):

  • service_discovery_errors_total{operation="registerService"} > 2 per minute - Warning
  • service_discovery_duration_seconds{operation="lookupService"} > 200ms p99 - Warning
  • service_instances_count{service_name="user-service"} < 1 - Warning (for critical services)

Alerting Configuration:

  • Slack notifications for all critical alerts
  • PagerDuty escalation for critical alert thresholds
  • Alert grouping by service name and operation type
  • Alert suppression during maintenance windows

14. Open Questions, Risks & Trade-offs

Decisions requiring product / engineering alignment

  • Service registration interval vs. heartbeat strategy: Should services register with fixed intervals or rely on heartbeats for liveness detection? This impacts system responsiveness to service failures and network partitions.
  • Service versioning strategy: How should services with different versions be handled in discovery? Should we support multiple versions simultaneously or enforce strict version compatibility?
  • Fallback mechanism for service discovery: What happens when the service registry becomes unavailable? Should services fall back to cached information or fail fast?

Known trade-offs and justifications

Trade-offOption 1Option 2Justification
Consistency vs. AvailabilityStrong consistency with quorum-based writesEventual consistency with optimistic updatesFor service discovery, availability is typically more critical than immediate consistency to avoid cascading failures
Centralized vs. Distributed RegistrySingle point of failureComplex coordination logicCentralized registry simplifies implementation and provides better consistency guarantees
Real-time vs. Polling-based UpdatesReal-time push notificationsPeriodic pollingPush requires more complex infrastructure but provides better latency for service changes
Service Registration vs. Health CheckSingle registration with periodic health checksSeparate registration and health check mechanismsSimpler to implement but may miss transient failures

Risks and mitigation strategies

  • Network Partition Risk: In a distributed system, network partitions can cause split-brain scenarios where services think they're the only ones available.

    • Mitigation: Implement a quorum-based approach where a majority of registry instances must agree on service state changes before propagation.
  • Service Registration Storm: When many services restart simultaneously, they can overwhelm the registry with registration requests.

    • Mitigation: Implement exponential backoff and jitter in service registration logic, and use rate limiting at the registry level.
  • Cache Invalidation Latency: Services may continue to route traffic to unhealthy instances due to stale cache entries.

    • Mitigation: Implement aggressive TTLs for service discovery caches and use distributed locks to ensure cache consistency during updates.
  • Registry Scalability Bottleneck: As the number of services grows, the registry can become a performance bottleneck.

    • Mitigation: Implement sharding strategies and use read replicas for high-availability.

Technical debt acknowledged

  • Service Registration Complexity: The current implementation assumes services will always send heartbeats, but in practice, some services may not support this pattern or may have intermittent connectivity.
  • Versioning Ambiguity: Service version handling is not fully specified, which could lead to compatibility issues in a multi-version environment.
  • Fallback Implementation Gaps: The fallback behavior when registry is unavailable is not fully implemented and needs more robust testing.
  • Monitoring Coverage: While observability is addressed, the actual monitoring implementation and alerting thresholds are not fully fleshed out in this design.
  • Cross-Region Service Discovery: The design does not address cross-region service discovery patterns, which could be critical for global deployments.
  • Service Metadata Management: The design assumes basic metadata fields but doesn't specify how complex metadata (tags, labels) will be managed or queried efficiently.

Was this article helpful?

Topics in this article

More from Backend LLD

  • Backend LLD

    Dynamic Configuration Service Low-Level Design

    Comprehensive LLD for a scalable dynamic configuration service with real-time updates, versioning, and multi-environment support.

  • Backend HLD

    API Rate Limiter Design and Implementation

    Comprehensive backend system design for rate limiting APIs with token bucket and sliding window algorithms, including distributed architecture considerations.

  • Backend LLD

    CQRS Framework Design and Implementation

    Comprehensive low-level design for a Command Query Responsibility Segregation (CQRS) framework with event sourcing, read/write model separation, and distributed consistency patterns.

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.