Skip to main content

Service Registry Low-Level Design for Microservices Architecture

Comprehensive LLD document covering service registry implementation with registration, discovery, and health monitoring for distributed microservices.

A service registry is a critical component in microservices architectures that enables dynamic service discovery, health monitoring, and load balancing across distributed systems. This document presents a comprehensive low-level design approach for building a robust service registry system that handles service registration, discovery, and failure detection at scale.

1. Problem Statement & Requirements

Clarifying questions

  1. What scale expectations are there for the service registry?

    • How many services and instances are we expecting to register?
    • What is the expected rate of service registration/deregistration events?
  2. What consistency requirements exist for service discovery?

    • Is strong consistency required, or eventual consistency acceptable?
    • What is the tolerance for stale service information?
  3. What are the key entities and their relationships in the system?

    • Are services, instances, and health checks separate entities?
    • How does the registry handle service versioning or multiple endpoints?
  4. What is the read/write ratio for service information?

    • Is service discovery (reads) significantly more frequent than registration (writes)?
    • How does this impact caching and consistency strategies?
  5. What are the latency sensitivity requirements?

    • What is the maximum acceptable latency for service discovery?
    • Are there any real-time or near-real-time constraints?
  6. What authentication and authorization model is expected?

    • Should services register with tokens or certificates?
    • Is there a need for role-based access control (RBAC) on service registration?
  7. Are there any external integrations or dependencies?

    • Will the registry integrate with service mesh, load balancers, or orchestration platforms (e.g., Kubernetes)?
    • Will it support external health check endpoints or need to integrate with monitoring systems?

Functional requirements

  • Service Registration: Services can register themselves with the registry, providing metadata (name, version, endpoints, health status).
  • Service Discovery: Clients can query the registry to discover available instances of a specific service.
  • Health Check Integration: Registry supports periodic health checks and updates instance status.
  • Service Deregistration: Services can deregister themselves or be automatically deregistered after timeout.
  • Service Metadata Management: Registry stores and retrieves metadata associated with services (tags, labels, configuration).
  • Instance Lifecycle Management: Registry tracks instance lifecycle including registration, heartbeat, and expiration.

Non-functional requirements

  • Latency Targets:

    • p50: <5ms for service discovery
    • p95: <10ms for service discovery
    • p99: <50ms for service discovery
  • Throughput:

    • 10,000 registration/deregistration events per second
    • 50,000 service discovery queries per second
  • Availability:

    • 99.9% uptime (43.2 minutes of downtime per month)
    • High availability across multiple data centers or regions

Constraints and assumptions

  • Assumptions:

    • Services are registered with a unique identifier (e.g., service name + version)
    • Services can register multiple instances with different endpoints
    • Health checks are performed by the services themselves or via external systems
    • The registry is designed to be a standalone component, not tightly coupled with service mesh or orchestration platforms
  • Constraints:

    • Registry must support horizontal scaling (sharding of services)
    • Services may be registered from different environments (dev, staging, prod)
    • Registry must support graceful degradation during partial outages

Out of scope

  • Service Mesh Integration: Detailed integration with Istio, Consul, or Linkerd
  • Service Configuration Management: Not part of this design (e.g., dynamic config updates)
  • Service Versioning Strategy: How services are versioned or updated (e.g., blue/green deployments)
  • Service Monitoring & Alerting: Integration with monitoring systems like Prometheus or Grafana
  • Cross-Region Failover: Multi-region replication and failover strategies
  • API Gateway Integration: Not part of this design (e.g., routing to services via gateway)
  • Service Authentication & Authorization: Not part of this design (e.g., OAuth2 integration for service registration)
  • Service Metrics Collection: Not part of this design (e.g., collecting metrics from services)

2. API Design

API Style Selection

gRPC with Protocol Buffers is selected for the Service Registry API due to:

  • Strong typing and automatic code generation
  • Efficient binary serialization (better than JSON for high-throughput)
  • Native support for streaming and bidirectional communication
  • First-class support for versioning and schema evolution
  • Built-in authentication and authorization support

Endpoint Definitions

MethodPathDescriptionAuth
RegisterService/serviceregistry.v1.ServiceRegistry/RegisterServiceRegister a new service instanceJWT
DeregisterService/serviceregistry.v1.ServiceRegistry/DeregisterServiceRemove a service instance from registryJWT
FindServices/serviceregistry.v1.ServiceRegistry/FindServicesQuery services by criteriaJWT
GetAllServices/serviceregistry.v1.ServiceRegistry/GetAllServicesGet all registered servicesJWT
Heartbeat/serviceregistry.v1.ServiceRegistry/HeartbeatService heartbeat for TTL managementJWT
GetServiceStatus/serviceregistry.v1.ServiceRegistry/GetServiceStatusGet status of specific service instanceJWT

Request and Response Schemas

RegisterServiceRequest

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

RegisterServiceResponse

message RegisterServiceResponse {
  string service_id = 1;
  int64 registered_at = 2;
}

FindServicesRequest

message FindServicesRequest {
  string service_name = 1;
  string version = 2;
  map<string, string> filters = 3;
  int32 limit = 4;
  int32 offset = 5;
}

FindServicesResponse

message FindServicesResponse {
  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 endpoints = 6;
  map<string, string> metadata = 7;
  int64 registered_at = 8;
  int64 last_heartbeat = 9;
  bool is_healthy = 10;
  string health_check_endpoint = 11;
}

HTTP Status Codes and Error Response

Standard HTTP status codes:

  • 200 OK for successful operations
  • 400 Bad Request for validation errors
  • 401 Unauthorized for auth failures
  • 403 Forbidden for access denied
  • 404 Not Found for missing resources
  • 500 Internal Server Error for server failures

Standardized error response:

{
  "error": {
    "code": "SERVICE_NOT_FOUND",
    "message": "Service with ID 'svc-123' not found",
    "details": {
      "service_id": "svc-123"
    }
  }
}

API Versioning Strategy

Versioned using semantic versioning in the gRPC package name:

  • serviceregistry.v1 - Current stable version
  • Future: serviceregistry.v2 for breaking changes

Pagination Design

Cursor-based pagination is used because:

  • More efficient than offset-based for large datasets
  • Consistent results even when data changes during pagination
  • Better performance with large offsets

Authentication and Authorization

All endpoints require JWT tokens with the following scopes:

  • service:register - for RegisterService and Heartbeat
  • service:read - for FindServices, GetAllServices, GetServiceStatus

Rate Limiting

Rate limiting per endpoint:

  • RegisterService: 100 req/min
  • Heartbeat: 500 req/min
  • FindServices: 200 req/min
  • GetAllServices: 50 req/min

Implementation uses Redis-based token bucket algorithm with per-service ID rate limiting.

Idempotency Design

For mutation endpoints:

  • idempotency_key field in request
  • Service ID used as key for deduplication
  • Store last operation timestamp and result in Redis
  • Return same response for duplicate requests within 5 seconds

Example Request/Response Flow

RegisterService

{
  "service_id": "svc-123",
  "service_name": "user-service",
  "version": "v1.2.3",
  "host": "10.0.1.5",
  "port": 8080,
  "endpoints": ["/api/users", "/api/auth"],
  "metadata": {
    "region": "us-west-1",
    "environment": "production"
  },
  "ttl_seconds": 30,
  "health_check_endpoint": "/health"
}
{
  "service_id": "svc-123",
  "registered_at": 1678886400
}

3. Data Model Design

Entity-Relationship Diagram

erDiagram
    SERVICE {
        string id PK
        string name
        string version
        string status
        string healthCheckUrl
        string serviceUrl
        timestamp createdAt
        timestamp updatedAt
        timestamp lastHeartbeat
        boolean isHealthy
    }

    SERVICE_INSTANCE {
        string id PK
        string serviceId FK
        string instanceId
        string host
        int port
        string status
        timestamp createdAt
        timestamp updatedAt
        timestamp lastHeartbeat
        boolean isHealthy
    }

    SERVICE_HEALTH {
        string id PK
        string serviceInstanceId FK
        string status
        timestamp recordedAt
        int responseTimeMs
        string message
    }

    SERVICE {
        1 -- 0..* SERVICE_INSTANCE : "has"
        1 -- 0..* SERVICE_HEALTH : "has"
    }

Table / Collection Schema Definitions

Service Table

CREATE TABLE services (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    version VARCHAR(50),
    status VARCHAR(50) DEFAULT 'ACTIVE',
    health_check_url TEXT,
    service_url TEXT NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    last_heartbeat TIMESTAMP WITH TIME ZONE,
    is_healthy BOOLEAN DEFAULT TRUE,
    
    INDEX idx_services_name (name),
    INDEX idx_services_status (status),
    INDEX idx_services_last_heartbeat (last_heartbeat)
);

Service Instance 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(50) DEFAULT 'ACTIVE',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    last_heartbeat TIMESTAMP WITH TIME ZONE,
    is_healthy BOOLEAN DEFAULT TRUE,
    
    INDEX idx_service_instances_service_id (service_id),
    INDEX idx_service_instances_instance_id (instance_id),
    INDEX idx_service_instances_host_port (host, port),
    INDEX idx_service_instances_status (status),
    INDEX idx_service_instances_last_heartbeat (last_heartbeat),
    
    UNIQUE(service_id, instance_id)
);

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(50) NOT NULL,
    recorded_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    response_time_ms INTEGER,
    message TEXT,
    
    INDEX idx_service_health_service_instance_id (service_instance_id),
    INDEX idx_service_health_recorded_at (recorded_at),
    INDEX idx_service_health_status (status)
);

Primary Key Strategy

UUIDs are used for all primary keys because:

  • Global uniqueness: No coordination required across services or regions
  • Scalability: Distributed systems can generate IDs without conflicts
  • Auditability: Easier to trace and correlate events across systems
  • No sequential patterns: Reduces predictability for security concerns

Index Design

Index NameFieldsTypePurpose
idx_services_namenameStandardFast service lookup by name
idx_services_statusstatusStandardFilter services by status
idx_services_last_heartbeatlast_heartbeatStandardIdentify stale services
idx_service_instances_service_idservice_idStandardFast instance lookup by service
idx_service_instances_instance_idinstance_idUniqueFast instance lookup
idx_service_instances_host_porthost, portStandardFind instances by host/port
idx_service_instances_statusstatusStandardFilter instances by status
idx_service_instances_last_heartbeatlast_heartbeatStandardIdentify stale instances
idx_service_health_service_instance_idservice_instance_idStandardFast health record lookup
idx_service_health_recorded_atrecorded_atStandardTime-series queries
idx_service_health_statusstatusStandardFilter health by status

Data Partitioning / Sharding Strategy

Sharding by Service Name Prefix:

  • Services are partitioned by the first character of their name (e.g., services starting with 'a' go to shard 0, 'b' to shard 1, etc.)
  • This ensures even distribution and allows for horizontal scaling
  • Each partition maintains a consistent set of services with similar prefixes

Soft Delete vs. Hard Delete Decision

Soft Delete: Services and instances are soft-deleted using a status field rather than physical deletion.

Justification:

  • Audit Trail: Historical data is preserved for compliance and debugging
  • Recovery: Services can be restored if accidentally deleted
  • Consistency: Avoids breaking dependent systems that might reference deleted services
  • Analytics: Historical service availability can be analyzed over time

Audit Trail Design

All data modifications are logged with:

  • created_by (user/service identifier)
  • updated_by (user/service identifier)
  • operation_type (CREATE, UPDATE, DELETE)
  • timestamp
  • old_values and new_values (for updates)

Data Archival Strategy and Retention Policy

Archival Strategy:

  • Services that have been inactive for 90+ days are archived
  • Archived services are moved to a separate archive table with reduced indexing
  • Historical health data is retained for 30 days in the primary tables

Retention Policy:

  • Active services: Keep indefinitely
  • Inactive services (last heartbeat > 90 days): Archive after 30 days
  • Health records: Keep for 30 days, then move to cold storage
  • Audit logs: Keep for 1 year
public class Service {
    private String id;
    private String name;
    private String version;
    private String status;
    private String healthCheckUrl;
    private String serviceUrl;
    private Instant createdAt;
    private Instant updatedAt;
    private Instant lastHeartbeat;
    private boolean isHealthy;
    
    // Getters and setters
}

4. Class Design & Service Layer

UML Class Diagram

classDiagram
    class ServiceRegistry {
        +registerService(Service)
        +deregisterService(String)
        +findServices(String, String)
        +heartbeat(String)
        +getServiceStatus(String)
        -validateService(Service)
        -updateServiceHealth(String, HealthStatus)
    }

    class Service {
        +id: String
        +name: String
        +version: String
        +status: ServiceStatus
        +healthCheckEndpoint: String
        +lastHeartbeat: Instant
        +createdAt: Instant
        +updatedAt: Instant
        +metadata: Map~String, String~
    }

    class HealthStatus {
        +status: Status
        +message: String
        +timestamp: Instant
    }

    class ServiceStatus {
        +ACTIVE
        +DEGRADED
        +UNHEALTHY
        +INACTIVE
    }

    class ServiceInstance {
        +id: String
        +serviceId: String
        +host: String
        +port: int
        +protocol: String
        +lastHeartbeat: Instant
    }

    class ServiceDiscovery {
        +discoverServices(String, String)
        +getInstances(String)
        +getServiceMetadata(String)
    }

    class HealthChecker {
        +checkHealth(ServiceInstance)
        +scheduleHealthChecks()
    }

    ServiceRegistry --> Service : manages
    ServiceRegistry --> HealthStatus : updates
    ServiceRegistry --> ServiceInstance : maintains
    Service --> HealthStatus : has
    Service --> ServiceInstance : has
    ServiceDiscovery --> ServiceRegistry : queries
    HealthChecker --> ServiceRegistry : updates

State Machine Diagram

stateDiagram-v2
    [*] --> ACTIVE
    ACTIVE --> DEGRADED : health_check_failed
    ACTIVE --> INACTIVE : heartbeat_timeout
    DEGRADED --> ACTIVE : health_restored
    DEGRADED --> UNHEALTHY : continued_failures
    UNHEALTHY --> INACTIVE : timeout
    INACTIVE --> ACTIVE : heartbeat_received

Service Class Structure and Responsibilities

The ServiceRegistry is the primary service responsible for managing service lifecycle, health monitoring, and discovery. It encapsulates:

  1. Service registration and lifecycle management
  2. Health status tracking and updates
  3. Service discovery capabilities
  4. Heartbeat monitoring and timeout handling

Interface Design

public interface ServiceRegistryService {
    void registerService(Service service);
    void deregisterService(String serviceId);
    List<Service> findServices(String name, String version);
    void heartbeat(String serviceId);
    ServiceStatus getServiceStatus(String serviceId);
    List<ServiceInstance> getInstances(String serviceId);
}

public interface HealthCheckService {
    void checkHealth(ServiceInstance instance);
    void scheduleHealthChecks();
}

Business Logic Encapsulation Patterns

Strategy Pattern for Health Check Implementation

public interface HealthCheckStrategy {
    HealthStatus checkHealth(ServiceInstance instance);
}

@Component
public class HttpHealthCheckStrategy implements HealthCheckStrategy {
    private final RestTemplate restTemplate;
    
    @Override
    public HealthStatus checkHealth(ServiceInstance instance) {
        try {
            String healthUrl = buildHealthUrl(instance);
            ResponseEntity<String> response = restTemplate.getForEntity(
                healthUrl, String.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                return new HealthStatus(HealthStatus.Status.HEALTHY, 
                    "Service is healthy", Instant.now());
            }
            
            return new HealthStatus(HealthStatus.Status.UNHEALTHY, 
                "Service returned error: " + response.getStatusCode(), 
                Instant.now());
        } catch (Exception e) {
            return new HealthStatus(HealthStatus.Status.UNHEALTHY, 
                "Health check failed: " + e.getMessage(), Instant.now());
        }
    }
    
    private String buildHealthUrl(ServiceInstance instance) {
        return String.format("%s://%s:%d%s", 
            instance.getProtocol(), 
            instance.getHost(), 
            instance.getPort(), 
            instance.getHealthCheckEndpoint());
    }
}

Critical-Path Method Implementation

@Transactional
public void heartbeat(String serviceId) {
    // Transaction boundary: entire heartbeat operation is atomic
    
    Service service = serviceRepository.findById(serviceId)
        .orElseThrow(() -> new ServiceNotFoundException("Service not found: " + serviceId));
    
    // Optimistic locking for concurrent updates
    int expectedVersion = service.getVersion();
    
    try {
        // Update last heartbeat timestamp
        service.setLastHeartbeat(Instant.now());
        
        // Validate and update health status
        HealthStatus currentHealth = healthCheckService.checkHealth(
            service.getInstance());
        
        service.setHealthStatus(currentHealth);
        
        // Update service in DB with version check
        int updatedRows = serviceRepository.updateWithVersion(
            service.getId(), 
            service.getLastHeartbeat(),
            service.getHealthStatus(),
            expectedVersion);
        
        if (updatedRows == 0) {
            throw new ConcurrencyException("Service was modified concurrently");
        }
        
        // Publish event for monitoring systems
        eventPublisher.publish(new ServiceHeartbeatEvent(
            serviceId, 
            currentHealth.getStatus().toString(),
            Instant.now()));
            
    } catch (Exception e) {
        // Log and re-throw to ensure transaction rollback
        logger.error("Failed to process heartbeat for service {}", serviceId, e);
        throw new ServiceRegistryException("Heartbeat processing failed", e);
    }
}

Transaction Boundary Design

Each service operation is wrapped in a transaction:

  • Service registration: Single DB write with validation
  • Heartbeat updates: Optimistic locking to prevent concurrent modification conflicts
  • Service deregistration: Atomic delete with cascading cleanup

Service Interface Contracts

public interface ServiceRegistryService {
    void registerService(Service service);
    void deregisterService(String serviceId);
    List<Service> findServices(String name, String version);
    void heartbeat(String serviceId);
    ServiceStatus getServiceStatus(String serviceId);
    List<ServiceInstance> getInstances(String serviceId);
}

Saga/Orchestration Pattern

For distributed operations like cross-service registration or health check propagation, we use a simple orchestration pattern:

public class ServiceRegistrationSaga {
    private final EventPublisher eventPublisher;
    
    public void executeRegistrationSaga(Service service) {
        try {
            // Step 1: Register in primary registry
            serviceRegistry.registerService(service);
            
            // Step 2: Notify discovery service
            eventPublisher.publish(new ServiceRegisteredEvent(service));
            
            // Step 3: Start health monitoring
            healthChecker.scheduleHealthChecks();
            
        } catch (Exception e) {
            // Rollback: deregister service and notify failure
            serviceRegistry.deregisterService(service.getId());
            eventPublisher.publish(new ServiceRegistrationFailedEvent(service, e));
            throw new SagaExecutionException("Registration saga failed", e);
        }
    }
}

Domain Object Design

@Entity
@Table(name = "services")
public class Service {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String id;
    
    @Column(nullable = false)
    private String name;
    
    @Column
    private String version;
    
    @Enumerated(EnumType.STRING)
    private ServiceStatus status = ServiceStatus.ACTIVE;
    
    @Embedded
    private HealthStatus healthStatus;
    
    @Column(name = "last_heartbeat")
    private Instant lastHeartbeat;
    
    @Column(name = "created_at")
    private Instant createdAt;
    
    @Column(name = "updated_at")
    private Instant updatedAt;
    
    @ElementCollection
    @MapKeyColumn(name = "key")
    @Column(name = "value")
    private Map<String, String> metadata = new HashMap<>();
    
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "instance_id")
    private ServiceInstance instance;
    
    // Getters and setters
}

@Embeddable
public class HealthStatus {
    private HealthStatus.Status status;
    private String message;
    private Instant timestamp;
    
    public enum Status {
        HEALTHY, DEGRADED, UNHEALTHY, INACTIVE
    }
}

@Entity
@Table(name = "service_instances")
public class ServiceInstance {
    @Id
    private String id;
    
    @Column(name = "service_id")
    private String serviceId;
    
    @Column
    private String host;
    
    @Column
    private int port;
    
    @Column(name = "protocol")
    private String protocol = "http";
    
    @Column(name = "health_check_endpoint")
    private String healthCheckEndpoint = "/health";
    
    @Column(name = "last_heartbeat")
    private Instant lastHeartbeat;
}

5. Concurrency & Thread Safety

Concurrency Model

The service registry will operate in a multi-threaded environment where multiple service instances can register, update, and deregister concurrently. The concurrency model will leverage:

  • Java's java.util.concurrent package for thread-safe operations
  • Read-write locks for concurrent read-heavy workloads
  • Thread-local storage for request-scoped context management
  • Asynchronous processing via CompletableFuture and ExecutorService for non-blocking operations

Race Condition Prevention Strategy

Race conditions will be prevented through:

  1. Atomic Operations: Using java.util.concurrent.atomic classes for counter and status updates
  2. Synchronized Blocks: For critical sections where atomic operations aren't sufficient
  3. Lock-Free Data Structures: Using ConcurrentHashMap and CopyOnWriteArrayList for service lists
  4. Version-based Conflict Detection: Implementing optimistic locking with version numbers to detect and handle concurrent modifications

Optimistic vs. Pessimistic Locking Selection

Optimistic Locking is selected for the service registry because:

  • Read-heavy workload with infrequent updates
  • Low contention in typical usage patterns
  • Better performance under concurrent access
  • Service registration/deregistration is infrequent enough that conflict resolution is acceptable

Implementation approach:

public class ServiceRegistry {
    private final Map<String, ServiceInstance> services = new ConcurrentHashMap<>();
    
    public boolean updateService(String serviceId, ServiceInstance updatedInstance) {
        ServiceInstance existing = services.get(serviceId);
        if (existing == null) return false;
        
        // Compare version numbers to detect concurrent modifications
        if (existing.getVersion() != updatedInstance.getVersion()) {
            throw new ConcurrentModificationException("Service has been modified by another process");
        }
        
        // Update with incremented version
        ServiceInstance updated = updatedInstance.withIncrementedVersion();
        services.put(serviceId, updated);
        return true;
    }
}

Deadlock Prevention Strategy

Deadlock prevention mechanisms include:

  1. Lock Ordering: Services are always acquired in a consistent order (by service ID hash)
  2. Timeout-based Acquisition: Using tryLock() with timeout instead of blocking indefinitely
  3. Hierarchical Locking: Service instances are grouped by namespace to prevent circular dependencies
  4. Deadlock Detection: Periodic checks for lock cycles in the system

Idempotency Implementation for Concurrent Duplicate Requests

Idempotency is implemented through:

  1. Request Deduplication: Using a distributed cache (Redis) to track recent registration requests
  2. Idempotency Keys: Clients can provide idempotency keys for registration operations
  3. Versioned Operations: Service updates include version numbers to detect and reject stale operations
public class IdempotentServiceRegistry {
    private final RedisTemplate<String, String> redisTemplate;
    
    public boolean registerServiceIfNotExists(String serviceId, ServiceInstance instance) {
        String key = "service_registration:" + serviceId;
        String requestId = instance.getIdempotencyKey();
        
        // Check if this exact registration request was already processed
        String existingId = redisTemplate.opsForValue().get(key);
        if (existingId != null && existingId.equals(requestId)) {
            return true; // Already processed
        }
        
        // Proceed with registration
        boolean success = registerService(serviceId, instance);
        if (success) {
            // Mark this request as processed for 30 seconds
            redisTemplate.opsForValue().set(key, requestId, 30, TimeUnit.SECONDS);
        }
        return success;
    }
}

Thread Safety in Service Discovery

Service discovery operations must be thread-safe:

  • Read operations on service lists use CopyOnWriteArrayList for safe concurrent reads
  • Write operations are synchronized to prevent modification during iteration
  • Cache invalidation uses atomic reference updates to ensure consistency

Synchronization Primitives Used

  1. ReentrantReadWriteLock: For protecting service list access with multiple readers and single writer
  2. StampedLock: For fine-grained locking where performance is critical
  3. CountDownLatch: For service startup synchronization
  4. Semaphore: To limit concurrent service discovery operations

Performance Considerations

  • Minimize lock scope to reduce contention
  • Use lock-free data structures where possible
  • Implement batching for bulk operations to reduce synchronization overhead
  • Monitor thread pool usage and adjust accordingly

Concurrency Testing Strategy

  • Stress testing with concurrent registration/deregistration operations
  • Race condition detection using JMH microbenchmarks
  • Integration testing with multiple service instances registering simultaneously
  • Load testing to validate thread safety under high concurrent load

6. Sequence Diagrams for Key Flows

sequenceDiagram
    participant Client
    participant ServiceRegistry
    participant DiscoveryService
    participant HealthChecker

    Client->>ServiceRegistry: Register Service (POST /services)
    ServiceRegistry->>DiscoveryService: Store service metadata
    ServiceRegistry->>HealthChecker: Start health check
    ServiceRegistry-->>Client: 201 Created (Service ID)
    
    loop Health Checks
        HealthChecker->>DiscoveryService: Ping service endpoint
        DiscoveryService-->>HealthChecker: Status OK/FAIL
        alt Healthy
            HealthChecker->>DiscoveryService: Update service status
        else Unhealthy
            HealthChecker->>DiscoveryService: Mark service as unhealthy
        end
    end
sequenceDiagram
    participant Client
    participant ServiceRegistry
    participant DiscoveryService

    Client->>ServiceRegistry: Discover Services (GET /services?serviceType=payment)
    ServiceRegistry->>DiscoveryService: Query services by type
    DiscoveryService-->>ServiceRegistry: Return healthy service instances
    ServiceRegistry-->>Client: 200 OK (Service list)
    
    Client->>ServiceRegistry: Get Service Details (GET /services/{id})
    ServiceRegistry->>DiscoveryService: Fetch service by ID
    DiscoveryService-->>ServiceRegistry: Return service metadata
    ServiceRegistry-->>Client: 200 OK (Service details)
sequenceDiagram
    participant Service
    participant ServiceRegistry
    participant DiscoveryService
    participant EventPublisher

    Service->>ServiceRegistry: Heartbeat (PUT /services/{id}/heartbeat)
    ServiceRegistry->>DiscoveryService: Update last heartbeat timestamp
    DiscoveryService-->>ServiceRegistry: Acknowledge update
    ServiceRegistry->>EventPublisher: Publish service heartbeat event
    EventPublisher-->>ServiceRegistry: Event acknowledged
    
    Service->>ServiceRegistry: Deregister (DELETE /services/{id})
    ServiceRegistry->>DiscoveryService: Remove service from registry
    DiscoveryService-->>ServiceRegistry: Confirm removal
    ServiceRegistry->>EventPublisher: Publish service deregistered event
    EventPublisher-->>ServiceRegistry: Event acknowledged

7. Caching Design

Cache Strategy Selection

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

Cache Key Design

Cache keys will follow a structured namespace pattern:

service-registry:{service-name}:{version}:{instance-id}
service-registry:metadata:{service-name}
service-registry:health:{service-name}

TTL Configuration

Data TypeTTLReason
Service Instance Metadata30sFrequent updates, short-lived
Health Status15sHigh frequency, real-time monitoring
Service Metadata5mStable data, infrequent changes
Service List10mBulk operations, less frequent

Cache Eviction Policy

We'll implement LRU (Least Recently Used) eviction policy with a secondary TTL-based cleanup. This ensures that:

  • Frequently accessed services remain in cache
  • Memory pressure is managed automatically
  • Stale data doesn't accumulate indefinitely

Cache Stampede Prevention

To prevent cache stampedes:

  1. Probabilistic Early Expiry: 20% of TTL for cache entries to trigger refresh
  2. Distributed Locking: Using Redis distributed locks for cache warming
  3. Cache Warm-up Strategy: Pre-warm hot services during startup

Distributed Cache Architecture

We'll use Redis Cluster with:

  • 3 master nodes for data distribution
  • 3 replica nodes per shard for high availability
  • Redis Sentinel for automatic failover
  • Memory policy: allkeys-lru with 2GB memory limit per node

Cache Invalidation Strategy

Event-driven invalidation with the following approach:

  1. Service Registration/Unregistration: Immediate invalidation of metadata cache
  2. Health Status Changes: TTL-based refresh with 5s minimum interval
  3. Service Metadata Updates: Write-through to cache with immediate consistency
@Component
public class ServiceRegistryCache {
    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper;
    
    public void invalidateServiceInstance(String serviceName, String instanceId) {
        String key = "service-registry:" + serviceName + ":" + instanceId;
        redisTemplate.delete(key);
        
        // Invalidate metadata cache for the service
        String metadataKey = "service-registry:metadata:" + serviceName;
        redisTemplate.delete(metadataKey);
        
        // Publish cache invalidation event for distributed systems
        publishCacheInvalidationEvent(serviceName, instanceId);
    }
    
    public void updateServiceHealth(String serviceName, String healthStatus) {
        String key = "service-registry:health:" + serviceName;
        redisTemplate.opsForValue().set(key, healthStatus, 15, TimeUnit.SECONDS);
        
        // Trigger cache warm-up for service metadata if needed
        String metadataKey = "service-registry:metadata:" + serviceName;
        redisTemplate.expire(metadataKey, 5, TimeUnit.MINUTES);
    }
}

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 logic and database operations. Each entity has its own repository interface and implementation.

public interface ServiceRepository {
    Optional<Service> findById(UUID id);
    List<Service> findAll();
    List<Service> findByStatus(ServiceStatus status);
    Service save(Service service);
    void delete(UUID id);
    boolean existsById(UUID id);
}

public class ServiceRepositoryImpl implements ServiceRepository {
    private final JdbcTemplate jdbcTemplate;
    private final ObjectMapper objectMapper;
    
    public ServiceRepositoryImpl(JdbcTemplate jdbcTemplate, ObjectMapper objectMapper) {
        this.jdbcTemplate = jdbcTemplate;
        this.objectMapper = objectMapper;
    }
    
    @Override
    public Optional<Service> findById(UUID id) {
        String sql = "SELECT * FROM services WHERE id = ?";
        try {
            return Optional.of(jdbcTemplate.queryForObject(sql, new ServiceRowMapper(), id));
        } catch (EmptyResultDataAccessException e) {
            return Optional.empty();
        }
    }
    
    @Override
    public List<Service> findAll() {
        String sql = "SELECT * FROM services ORDER BY created_at DESC";
        return jdbcTemplate.query(sql, new ServiceRowMapper());
    }
    
    @Override
    public List<Service> findByStatus(ServiceStatus status) {
        String sql = "SELECT * FROM services WHERE status = ? ORDER BY created_at DESC";
        return jdbcTemplate.query(sql, new ServiceRowMapper(), status.name());
    }
    
    @Override
    public Service save(Service service) {
        if (service.getId() == null) {
            service.setId(UUID.randomUUID());
        }
        
        String sql = """
            INSERT INTO services (id, name, version, status, metadata, health_check_url, 
                                 last_heartbeat, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT (id) DO UPDATE SET 
                name = EXCLUDED.name,
                version = EXCLUDED.version,
                status = EXCLUDED.status,
                metadata = EXCLUDED.metadata,
                health_check_url = EXCLUDED.health_check_url,
                last_heartbeat = EXCLUDED.last_heartbeat,
                updated_at = EXCLUDED.updated_at
            """;
            
        jdbcTemplate.update(sql, 
            service.getId(),
            service.getName(),
            service.getVersion(),
            service.getStatus().name(),
            objectMapper.writeValueAsString(service.getMetadata()),
            service.getHealthCheckUrl(),
            service.getLastHeartbeat(),
            service.getCreatedAt(),
            service.getUpdatedAt()
        );
        
        return service;
    }
    
    @Override
    public void delete(UUID id) {
        String sql = "DELETE FROM services WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
    
    @Override
    public boolean existsById(UUID id) {
        String sql = "SELECT EXISTS(SELECT 1 FROM services WHERE id = ?)";
        return jdbcTemplate.queryForObject(sql, Boolean.class, id);
    }
}

ORM vs Raw Query Decisions

For this service registry, we use raw JDBC with JdbcTemplate instead of an ORM like Hibernate for the following reasons:

  1. Performance: Raw queries are more efficient for simple CRUD operations
  2. Control: Direct control over query execution and optimization
  3. Simplicity: Avoids ORM complexity for a straightforward data model
  4. Type Safety: Using prepared statements prevents SQL injection

Read vs Write Separation

We implement read-write separation using a CQRS-like approach:

public class ReadServiceRepository {
    private final JdbcTemplate readJdbcTemplate;
    
    public ReadServiceRepository(JdbcTemplate readJdbcTemplate) {
        this.readJdbcTemplate = readJdbcTemplate;
    }
    
    public List<Service> findActiveServices() {
        String sql = """
            SELECT s.*, 
                   CASE WHEN s.last_heartbeat > ? THEN 'HEALTHY' ELSE 'UNHEALTHY' END as status
            FROM services s 
            WHERE s.status = 'ACTIVE'
            """;
        return readJdbcTemplate.query(sql, new ServiceRowMapper(), 
            Instant.now().minus(Duration.ofMinutes(5)));
    }
    
    public ServiceSummary getSummary(UUID serviceId) {
        String sql = """
            SELECT id, name, version, status, last_heartbeat, created_at
            FROM services 
            WHERE id = ?
            """;
        return readJdbcTemplate.queryForObject(sql, new ServiceSummaryRowMapper(), serviceId);
    }
}

public class WriteServiceRepository {
    private final JdbcTemplate writeJdbcTemplate;
    
    public WriteServiceRepository(JdbcTemplate writeJdbcTemplate) {
        this.writeJdbcTemplate = writeJdbcTemplate;
    }
    
    public Service save(Service service) {
        // Implementation as above
        return service;
    }
}

Connection Pool Configuration

# application.yml
spring:
  datasource:
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5
      connection-timeout: 30000
      idle-timeout: 600000
      max-lifetime: 1800000
      validation-timeout: 5000
      leak-detection-threshold: 60000

N+1 Query Prevention Strategy

We prevent N+1 queries by:

  1. Eager Loading: Fetching related data in single queries
  2. Batch Operations: Using batch inserts/updates where appropriate
public class ServiceBatchRepository {
    private final JdbcTemplate jdbcTemplate;
    
    public void saveAll(List<Service> services) {
        String sql = """
            INSERT INTO services (id, name, version, status, metadata, health_check_url, 
                                 last_heartbeat, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT (id) DO UPDATE SET 
                name = EXCLUDED.name,
                version = EXCLUDED.version,
                status = EXCLUDED.status,
                metadata = EXCLUDED.metadata,
                health_check_url = EXCLUDED.health_check_url,
                last_heartbeat = EXCLUDED.last_heartbeat,
                updated_at = EXCLUDED.updated_at
            """;
            
        // Batch operation to prevent N+1
        jdbcTemplate.batchUpdate(services, (ps, service) -> {
            ps.setObject(1, service.getId());
            ps.setString(2, service.getName());
            ps.setString(3, service.getVersion());
            ps.setString(4, service.getStatus().name());
            ps.setString(5, objectMapper.writeValueAsString(service.getMetadata()));
            ps.setString(6, service.getHealthCheckUrl());
            ps.setTimestamp(7, Timestamp.from(service.getLastHeartbeat()));
            ps.setTimestamp(8, Timestamp.from(service.getCreatedAt()));
            ps.setTimestamp(9, Timestamp.from(service.getUpdatedAt()));
        });
    }
}

Data Access Layer Design Summary

The repository layer provides:

  • Clean abstraction over data access operations
  • Separation of concerns between domain logic and persistence
  • Read-write separation for performance optimization
  • Batch operation support to reduce database round trips
  • Prevention of N+1 query problems through eager loading and batch operations
  • Type-safe, SQL injection-resistant operations using prepared statements

This design enables efficient service registry operations while maintaining scalability and performance for high-throughput environments.

9. Asynchronous Processing & Messaging

Event-driven boundaries in this feature

The service registry operates primarily in a synchronous request-response model for core CRUD operations. However, asynchronous processing is essential for:

  1. Service heartbeat and health monitoring - Services periodically send heartbeats to detect failures
  2. Service lifecycle events - Registration, unregistration, status changes
  3. Configuration change propagation - When service configuration updates, they must be broadcast to dependent services
  4. Metrics aggregation and reporting - Aggregating service health metrics for dashboards

The decision to use async processing is driven by the need for real-time service discovery and health monitoring without blocking synchronous operations. Heartbeats and status changes are asynchronous to ensure that service registration doesn't block on health checks.

Message schema design

{
  "version": "1.0",
  "type": "service.heartbeat",
  "timestamp": "2023-10-27T10:30:00Z",
  "serviceId": "svc-1234567890",
  "serviceName": "user-service",
  "status": "healthy",
  "lastHeartbeat": "2023-10-27T10:29:30Z",
  "metadata": {
    "host": "10.0.1.5",
    "port": 8080,
    "version": "v1.2.3"
  }
}

The message schema uses JSON format with a version field for backward compatibility. Each event type has a clear naming convention (service.{event_type}) and includes service metadata that enables consumers to make informed decisions.

Dead letter queue strategy and poison message handling

Poison messages are handled through a dead-letter queue (DLQ) pattern:

  1. Retry mechanism: Messages that fail up to 3 times are retried with exponential backoff (1s, 2s, 4s)
  2. DLQ routing: Messages that fail after max retries are sent to a dedicated DLQ topic
  3. Manual intervention: DLQ messages are flagged for manual inspection and potential reprocessing

The system uses a circuit breaker pattern to prevent cascading failures when the DLQ is overwhelmed. If the DLQ consumer fails more than 5 times consecutively, it enters a half-open state to test recovery.

At-least-once vs. exactly-once delivery

At-least-once delivery is chosen for this feature because:

  1. Idempotency is built into service operations: Service registration and heartbeat updates are idempotent
  2. Eventual consistency is acceptable: The system tolerates temporary inconsistencies in service state
  3. Simpler implementation: Exactly-once requires distributed transaction coordination which adds complexity

The system uses message IDs to detect duplicates and ensures that duplicate events don't cause service state inconsistencies.

Retry policy for consumers

public class MessageRetryPolicy {
    private static final int MAX_RETRIES = 3;
    private static final long INITIAL_DELAY_MS = 1000;
    private static final double BACKOFF_MULTIPLIER = 2.0;
    private static final long MAX_DELAY_MS = 30000;

    public boolean shouldRetry(int attempt, Exception exception) {
        if (attempt >= MAX_RETRIES) {
            return false;
        }
        
        // Don't retry on non-recoverable errors
        if (exception instanceof IllegalArgumentException || 
            exception instanceof InvalidServiceException) {
            return false;
        }
        
        return true;
    }

    public long getDelay(int attempt) {
        long delay = (long) (INITIAL_DELAY_MS * Math.pow(BACKOFF_MULTIPLIER, attempt));
        return Math.min(delay, MAX_DELAY_MS);
    }
}

Outbox pattern for reliable event publishing

The outbox pattern is implemented in this design:

  1. Transaction boundary: Events are written to an event_outbox table within the same database transaction as the service state change
  2. Background processor: A separate daemon process polls the outbox table and publishes messages to the message broker
  3. Idempotency: Events are marked as published once successfully delivered to the broker

This pattern ensures that events are not lost even if the service crashes during event publishing, maintaining consistency between service state and published events.

Sequence diagram for async flows

sequenceDiagram
    participant Service
    participant Registry
    participant MessageBroker
    participant OutboxProcessor

    Service->>Registry: Register service (POST /services)
    Registry->>Registry: Validate and store service
    Registry->>OutboxProcessor: Insert event to outbox table
    OutboxProcessor->>MessageBroker: Publish heartbeat event (service.heartbeat)
    MessageBroker-->>Service: Event acknowledged
    Service->>Registry: Heartbeat (POST /services/{id}/heartbeat)
    Registry->>OutboxProcessor: Insert event to outbox table
    OutboxProcessor->>MessageBroker: Publish heartbeat event (service.heartbeat)

The async flow ensures that service registration and heartbeat events are reliably published to the message broker, enabling downstream consumers to react to service state changes in real-time. The outbox pattern guarantees that these events are not lost even if the service or database experiences temporary failures.

10. Error Handling Design

Error Classification Hierarchy

The error handling strategy follows a hierarchical classification system to enable appropriate response handling:

Error
├── DomainError (business logic violations)
│   ├── ValidationException
│   ├── BusinessLogicException
│   └── ConflictException
├── InfrastructureError (system-level issues)
│   ├── DatabaseException
│   ├── ExternalServiceException
│   └── TimeoutException
└── SystemError (internal system issues)
    ├── InternalServerException
    └── ConfigurationException

Error Propagation Strategy

Errors are propagated up the call stack with appropriate wrapping and context addition. Critical system errors (like configuration issues) are not wrapped to preserve stack traces for debugging, while domain and infrastructure errors are wrapped with meaningful context.

Retry Strategy

Retry logic is implemented using exponential backoff with jitter to prevent thundering herd:

public class RetryableOperation {
    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;
        while (attempts < MAX_RETRIES) {
            try {
                return operation.get();
            } catch (ExternalServiceException ex) {
                if (attempts >= MAX_RETRIES - 1) throw ex;
                
                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 InternalServerException("Retry interrupted", ie);
                }
                attempts++;
            }
        }
        throw new InternalServerException("Max retries exceeded");
    }
}

Circuit Breaker Design

For external service dependencies, a circuit breaker pattern is implemented using the Hystrix library or custom implementation:

public class CircuitBreaker {
    private volatile CircuitState state = CircuitState.CLOSED;
    private int failureCount = 0;
    private long lastFailureTime = 0;
    private static final int FAILURE_THRESHOLD = 5;
    private static final long TIMEOUT_MS = 60000;
    private static final long RESET_TIMEOUT_MS = 30000;

    public synchronized <T> T execute(Supplier<T> operation) {
        if (state == CircuitState.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > RESET_TIMEOUT_MS) {
                state = CircuitState.HALF_OPEN;
            } else {
                throw new ServiceUnavailableException("Circuit is open");
            }
        }

        try {
            T result = operation.get();
            if (state == CircuitState.HALF_OPEN) {
                state = CircuitState.CLOSED;
            }
            return result;
        } catch (Exception ex) {
            handleFailure();
            throw ex;
        }
    }

    private void handleFailure() {
        failureCount++;
        lastFailureTime = System.currentTimeMillis();
        
        if (failureCount >= FAILURE_THRESHOLD) {
            state = CircuitState.OPEN;
        }
    }

    enum CircuitState {
        CLOSED, OPEN, HALF_OPEN
    }
}

Fallback Behavior Design

Fallbacks are implemented for critical external dependencies:

public class ServiceRegistryService {
    private final ExternalHealthCheckService healthService;
    
    public ServiceInstance getHealthyInstance(String serviceId) {
        try {
            return healthService.getHealthyInstance(serviceId);
        } catch (ExternalServiceException ex) {
            // Fallback to cached healthy instances
            return getCachedHealthyInstance(serviceId);
        }
    }
}

Error Logging Format

Structured logging includes trace context and error details:

{
  "timestamp": "2023-10-15T14:30:45.123Z",
  "trace_id": "123e4567-e89b-12d3-a456-426614174000",
  "span_id": "abcdef1234567890",
  "user_id": null,
  "entity_id": "service-123",
  "error_code": "SERVICE_UNAVAILABLE",
  "error_message": "External health check service unavailable",
  "error_type": "InfrastructureError",
  "stack_trace": "...",
  "http_status": 503,
  "service_name": "health-check-service"
}

Alerting Thresholds

Critical alerts are configured for:

  • Service unavailability: >5% error rate over 5 minutes
  • High latency: p99 > 500ms for >10 minutes
  • Circuit breaker trips: >3 consecutive failures in 1 minute

Error Response Format

Standardized JSON error response:

{
  "error": {
    "code": "SERVICE_UNAVAILABLE",
    "message": "Service temporarily unavailable",
    "details": {
      "service_id": "health-check-service",
      "retry_after": 30
    }
  },
  "timestamp": "2023-10-15T14:30:45.123Z",
  "request_id": "req-abc123"
}

Error Handling in API Layer

All errors are caught and transformed to appropriate HTTP responses:

@RestController
public class ServiceRegistryController {
    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<ErrorResponse> handleValidation(ValidationException ex) {
        return ResponseEntity.badRequest()
            .body(new ErrorResponse("VALIDATION_ERROR", ex.getMessage()));
    }

    @ExceptionHandler(ExternalServiceException.class)
    public ResponseEntity<ErrorResponse> handleExternalService(ExternalServiceException ex) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
            .body(new ErrorResponse("EXTERNAL_SERVICE_ERROR", "Service temporarily unavailable"));
    }
}

11. Security Design

Input Validation and Sanitization Strategy

All service registry inputs undergo strict validation using a combination of:

  • Regex patterns for format validation (e.g., service name: ^[a-zA-Z0-9_-]{1,64}$)
  • Length limits (max 256 characters for metadata values)
  • Type checking using Jackson validation annotations
  • Custom validators for complex constraints (e.g., valid service port range 1-65535)
public class ServiceRegistrationRequest {
    @Pattern(regexp = "^[a-zA-Z0-9_-]{1,64}$", message = "Service name must be alphanumeric with dashes and underscores only")
    private String serviceName;
    
    @Min(value = 1, message = "Port must be between 1 and 65535")
    @Max(value = 65535, message = "Port must be between 1 and 65535")
    private Integer port;
    
    @NotNull
    private String host;
    
    @ValidMetadata
    private Map<String, String> metadata;
}

SQL Injection Prevention

All database interactions use parameterized queries exclusively. No dynamic query construction or string concatenation is permitted:

// Safe - parameterized query
String sql = "SELECT * FROM services WHERE service_name = ? AND status = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, serviceName);
stmt.setString(2, "ACTIVE");
ResultSet rs = stmt.executeQuery();

// Unsafe - never used
// String sql = "SELECT * FROM services WHERE service_name = '" + serviceName + "'";

Authentication Middleware Design

Authentication is handled via JWT tokens with a custom filter:

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtTokenProvider jwtTokenProvider;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                   HttpServletResponse response,
                                   FilterChain filterChain) throws ServletException, IOException {
        String token = extractToken(request);
        if (token != null && jwtTokenProvider.validateToken(token)) {
            Authentication auth = jwtTokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(request, response);
    }
}

Authorization Enforcement

RBAC-based authorization using Spring Security annotations:

@PreAuthorize("hasRole('ADMIN') or hasRole('SERVICE_REGISTRY_WRITE')")
public void registerService(ServiceRegistrationRequest request) {
    // Implementation
}

@PreAuthorize("hasRole('READER') or hasRole('ADMIN')")
public ServiceMetadata getService(String serviceName) {
    // Implementation
}

Sensitive Data Encryption

All sensitive data is encrypted at rest using AES-256:

@Service
public class EncryptionService {
    private final Cipher cipher;
    
    public String encrypt(String plaintext) {
        // AES-256 encryption with CBC mode and PKCS7 padding
        return Base64.getEncoder().encodeToString(
            cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8))
        );
    }
    
    public String decrypt(String encrypted) {
        // AES-256 decryption
        return new String(
            cipher.doFinal(Base64.getDecoder().decode(encrypted)),
            StandardCharsets.UTF_8
        );
    }
}

PII Handling and Masking Strategy

PII data is never stored in plaintext. Hostnames are masked for logging:

public class PiiMaskingUtil {
    public static String maskHostname(String hostname) {
        if (hostname == null || hostname.length() < 5) return hostname;
        return hostname.substring(0, 2) + "****" + hostname.substring(hostname.length() - 2);
    }
}

Secrets Management

Secrets (e.g., JWT signing keys) are managed via AWS Secrets Manager:

@Service
public class SecretManager {
    private final AWSSecretsManager secretsManager;
    
    public String getSecret(String secretName) {
        GetSecretValueRequest request = GetSecretValueRequest.builder()
            .secretId(secretName)
            .build();
        return secretsManager.getSecretValue(request).secretString();
    }
}

Audit Logging Design

All administrative actions are logged with full audit trail:

@EventListener
public void handleServiceRegistrationEvent(ServiceRegistrationEvent event) {
    AuditLog log = AuditLog.builder()
        .userId(event.getUserId())
        .action("SERVICE_REGISTERED")
        .resourceType("SERVICE")
        .resourceId(event.getServiceName())
        .timestamp(Instant.now())
        .details(Map.of(
            "host", event.getHost(),
            "port", event.getPort(),
            "metadata", event.getMetadata()
        ))
        .build();
    
    auditLogRepository.save(log);
}

12. Testing Strategy

Unit Testing Scope and Coverage Targets (%)

  • Service Layer: 85% code coverage with focus on business logic and error handling paths
  • Repository Layer: 90% coverage for all CRUD operations and query patterns
  • Domain Objects: 100% coverage for value objects, validation logic, and state transitions
  • API Layer: 80% coverage for request/response handling and validation logic
  • Integration Points: 75% coverage for external dependency mocks (e.g., cache, database)
  • Critical Paths: 100% coverage for all service methods that handle concurrent access and transaction boundaries

Integration Testing Strategy

  • Test Containers: Use Docker-based test containers for database (PostgreSQL) and cache (Redis) integration testing
  • Embedded Databases: H2 for fast unit tests with schema compatibility validation
  • WireMock: For external service stubbing (e.g., authentication provider, metrics collector)
  • Test Data Isolation: Each test runs in isolated database schema or with clean state between tests
  • Database Transaction Rollback: Use transactional test framework to rollback changes after each test

Contract Testing

  • Pact Framework: For consumer-provider contract testing between service registry and client services
  • Versioned Contracts: Maintain versioned contract files in repository for each major API change
  • Contract Validation: Run contract tests as part of CI pipeline to ensure compatibility between registry and service clients
  • Contract Evolution: Handle breaking changes with versioned contracts and backward compatibility checks

Performance Testing Tool

  • k6: Use k6 for load testing service registry under concurrent registration/deregistration scenarios
  • Key Scenarios:
    • Concurrent service registration (1000 concurrent requests)
    • High-frequency health checks (5000 concurrent heartbeat updates)
    • Service discovery under load (10,000 concurrent lookup requests)
  • Performance Targets:
    • p50 latency < 10ms for service discovery
    • p95 latency < 50ms for service registration
    • Throughput > 10,000 ops/sec for concurrent registrations

Test Data Management Strategy

  • Fixtures: Predefined JSON fixtures for common service registration scenarios (healthy, unhealthy, expired)
  • Factories: Factory classes for generating test service instances with varying configurations (e.g., different health check intervals, tags)
  • Seeding: Automated data seeding for integration tests using database migrations or test data builders
  • Test Data Cleanup: Implement automatic cleanup of test data in database and cache after each test run
  • Data Variants: Maintain test data variants for different service types, registration methods, and lifecycle states
// Example unit test for service registration with validation
@Test
public void testRegisterServiceWithInvalidPayload() {
    ServiceRegistrationRequest request = new ServiceRegistrationRequest();
    // Missing required fields - should throw validation error
    assertThrows(ValidationException.class, () -> serviceRegistry.registerService(request));
}

@Test
public void testRegisterServiceWithValidPayload() {
    ServiceRegistrationRequest request = ServiceFactory.createValidServiceRequest();
    
    Service service = serviceRegistry.registerService(request);
    
    assertNotNull(service.getId());
    assertEquals(request.getName(), service.getName());
    assertEquals(ServiceStatus.HEALTHY, service.getStatus());
    verify(cacheService).put(eq("service:" + service.getId()), any(Service.class));
}

13. Observability Design

Structured Logging Schema

All logs must follow a consistent schema with the following required fields:

{
  "timestamp": "2023-10-27T14:30:45.123Z",
  "level": "INFO|WARN|ERROR",
  "service": "service-registry",
  "trace_id": "1234567890abcdef1234567890abcdef",
  "span_id": "abcdef1234567890",
  "user_id": "user-123",
  "entity_id": "service-abc123",
  "operation": "registerService",
  "message": "Service registered successfully",
  "error_code": "SERVICE_ALREADY_EXISTS",
  "error_details": {
    "stack_trace": "...",
    "cause": "Service with name 'payment-service' already exists"
  },
  "duration_ms": 15,
  "host": "service-registry-7b5c8f9d4-xyz12"
}

PII masking rules:

  • User IDs and session tokens are masked in logs
  • IP addresses are truncated to network prefix (e.g., 192.168.0.0/24)
  • Sensitive fields like passwords or tokens are completely redacted

Distributed Tracing Instrumentation

Using OpenTelemetry with custom spans:

Key Operations to Trace:

  1. registerService - Service registration flow
  2. deregisterService - Service de-registration flow
  3. getServiceStatus - Health check query
  4. heartbeat - Service heartbeat processing

Span Attributes:

  • service.name: Name of the service being operated on
  • service.id: Unique identifier for the service instance
  • service.status: Current status (HEALTHY, UNHEALTHY, DEGRADED)
  • service.version: Semantic version of the service
  • service.host: Host address where service is running
  • request.duration.ms: Duration of the operation in milliseconds

Metrics Design

RED Method Metrics:

Metric NameTypeLabelsDescription
service_registry_requests_totalCountermethod, endpoint, status_codeTotal count of all service registry API requests
service_registry_errors_totalCountermethod, error_typeCount of failed requests
service_registry_request_duration_secondsHistogrammethod, endpointResponse time distribution
service_registry_active_servicesGaugestatusCurrent count of active services by status
service_registry_heartbeat_failures_totalCounterservice_idHeartbeat failure count per service
service_registry_cache_hit_ratioGaugetypeCache hit ratio for service lookups

Service Health Metrics:

  • service_health_status - Gauge with status labels (HEALTHY, UNHEALTHY, DEGRADED)
  • service_heartbeat_age_seconds - Histogram showing time since last heartbeat

Health Check Endpoint Design

GET /health
GET /ready  
GET /live
GET /startup

/health - Returns service operational status:

{
  "status": "healthy",
  "checks": {
    "database": "healthy",
    "cache": "healthy",
    "message_queue": "healthy"
  }
}

/ready - Returns readiness for serving traffic:

{
  "status": "ready",
  "dependencies": {
    "database": "connected",
    "redis": "connected"
  }
}

/live - Returns liveness (service is running):

{
  "status": "alive",
  "uptime_seconds": 3600,
  "version": "1.2.3"
}

/startup - Returns startup completion status:

{
  "status": "complete",
  "startup_time_ms": 1500,
  "dependencies_loaded": true
}

Alerting Thresholds

MetricWarning ThresholdCritical ThresholdAlert Channel
service_registry_errors_total (5m rate)> 10 errors/minute> 50 errors/minuteOn-call
service_registry_request_duration_seconds (p99)> 500ms> 2sOn-call
service_registry_active_services (count)< 50% of expected< 25% of expectedSlack
service_registry_cache_hit_ratio< 70%< 50%Slack
service_registry_heartbeat_failures_total (5m rate)> 5 failures/minute> 20 failures/minuteOn-call

On-call escalation path:

  1. Primary engineer (5 min response)
  2. Secondary engineer (30 min response)
  3. Engineering manager (1 hour response)

Service-Level Instrumentation

Each service registry operation should include:

  • Request context with trace_id and span_id
  • Operation duration tracking
  • Error rate monitoring
  • Cache hit/miss ratio tracking
  • Database query count and duration

Log Rotation & Retention

Log rotation based on size (100MB) and time (24h). Retention policy: 30 days for operational logs, 90 days for audit logs. Log aggregation using ELK stack with centralized logging and search capabilities.

14. Open Questions, Risks & Trade-offs

Decisions requiring product / engineering alignment

  • Service registration heartbeat interval: What is the acceptable grace period before considering a service unhealthy? This directly impacts latency sensitivity and network reliability assumptions.
  • Service versioning strategy: Should services be registered with specific versions or use semantic versioning for compatibility? This affects backward compatibility and rollout strategies.
  • Service discovery protocol: Should we support multiple protocols (gRPC, HTTP, gRPC-Gateway) or focus on one? This impacts client complexity and ecosystem integration.
  • Service metadata schema: How granular should service metadata be? Should we support custom tags, health check endpoints, or just basic attributes?

Known trade-offs and justifications

Trade-offImpactJustification
Consistency vs. AvailabilityHighUsing eventual consistency for service health status allows the registry to remain available even during partial outages. For a service registry, availability is more critical than immediate consistency since services can recover and re-register.
Centralized vs. Distributed RegistryModerateA centralized registry provides simpler management and consistent view but creates a single point of failure. Distributed approaches like etcd or Consul offer better fault tolerance but increase complexity in maintaining consistency and handling network partitions.
In-memory vs. Persistent StorageModerateIn-memory storage offers better performance but loses state on restarts. Persistent storage ensures durability but introduces latency and complexity in managing disk I/O and recovery scenarios.
Service Registration vs. Service DiscoveryLowPrioritizing fast service discovery over registration speed allows us to optimize for read-heavy workloads, which are more common in typical service mesh usage patterns.

Risks and mitigation strategies

RiskImpactMitigation
Network partitionsHighImplement circuit breaker patterns and use distributed consensus protocols like Raft to maintain quorum-based availability.
Service spammingMediumEnforce rate limiting on registration endpoints and implement TTL-based cleanup for stale services.
High memory usageMediumUse efficient data structures and implement periodic garbage collection for expired services.
Cache inconsistencyMediumImplement cache invalidation strategies and use versioned keys to ensure data consistency across nodes.
Security vulnerabilitiesHighImplement strict authentication and authorization for service registration and discovery endpoints.

Technical debt acknowledged

  • Service metadata schema evolution: The current design assumes a fixed set of metadata fields, which may not scale well with evolving service requirements. Future versions might require schema migration strategies or flexible metadata handling.
  • Heartbeat mechanism complexity: The heartbeat-based health check system introduces additional complexity in managing service lifecycle and handling network partitions. This could be simplified with external health check integrations.
  • Service versioning limitations: The current implementation does not support complex versioning strategies like canary deployments or A/B testing. These would require more sophisticated service registration and discovery mechanisms.
  • Lack of multi-region support: The design assumes a single region or data center, which may not be suitable for global deployments. Multi-region support would require additional complexity in managing cross-region service discovery and replication.
  • No service dependency tracking: The system currently does not track service dependencies or provide circuit breaker integration, which could lead to cascading failures in complex microservice architectures.

Was this article helpful?

Topics in this article

More from Backend LLD

  • 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.

  • 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.

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.