Skip to main content

Change Data Capture Processor Design and Implementation

Comprehensive low-level design for a scalable Change Data Capture system that captures, processes, and delivers database changes in real-time.

A Change Data Capture processor enables real-time data synchronization by capturing database modifications and delivering them to downstream systems for analytics, caching, or replication purposes. This design covers the core architecture, data flow, and implementation patterns for building a robust CDC solution.

1. Problem Statement & Requirements

Clarifying questions

  1. What is the scope of data sources for CDC? Will we support only relational databases (MySQL, PostgreSQL), or will we also handle NoSQL systems like MongoDB?
  2. What is the expected scale of data changes? Are we dealing with high-volume transactional systems (e.g., 100k+ changes per second) or moderate-scale systems?
  3. What consistency guarantees are required? Should we ensure exactly-once delivery of events, or is at-least-once acceptable?
  4. What are the downstream consumers of these change events? Are they primarily internal microservices, or external partners?
  5. What is the expected latency for event delivery? Should we aim for sub-second delivery or can we tolerate higher latencies?
  6. What is the expected retention period for change events? Do we need to support long-term event storage or just recent changes?
  7. What are the compliance and audit requirements? Do we need to support audit trails or regulatory reporting?

Functional requirements

  • Capture real-time data changes (inserts, updates, deletes) from source databases
  • Transform captured events into standardized format for downstream consumption
  • Publish change events to message queue or event store for asynchronous processing
  • Support multiple database sources (MySQL, PostgreSQL, Oracle)
  • Provide ability to filter and route events based on table/schema rules
  • Maintain event ordering within a single database transaction
  • Support event replay capability for downstream systems to recover from failures

Non-functional requirements

  • Latency targets: p50 < 10ms, p95 < 50ms, p99 < 200ms for event processing
  • Throughput: Support 10,000+ events/sec with sub-second delivery latency
  • Availability: 99.9% uptime for the CDC processor with automatic failover capability
  • Scalability: Horizontal scaling capability to support multiple database sources and consumers
  • Reliability: At-least-once delivery guarantee for all change events

Constraints and assumptions

  • Source databases are assumed to support logical replication or binlog/transaction log capture
  • Message broker (e.g., Kafka) is already provisioned and managed by the system
  • Database credentials and connection details are securely managed via a secrets manager
  • Change event payloads will be serialized in JSON format for interoperability
  • Assumption of stable database schemas with minimal schema drift during operation
  • No requirement for real-time event deduplication across multiple database sources

Out of scope

  • Database schema migration or transformation logic (this is handled by the consuming services)
  • Change event compression or deduplication at the source level (handled by message brokers)
  • Database backup or recovery capabilities (external systems handle this)
  • Change event filtering based on content (e.g., specific field values) — only table-level filtering is supported
  • Multi-source replication coordination (each database source is handled independently)
  • Change event encryption at rest (handled by the message broker or storage layer)

2. API Design

API Style Selection

For Change Data Capture (CDC) processor, I'll select gRPC as the primary API style:

  • Advantages:

    • Efficient binary protocol with lower network overhead
    • Strong typing and automatic code generation for all supported languages
    • Built-in support for streaming RPCs (ideal for real-time CDC events)
    • Better performance characteristics for high-throughput scenarios
    • Native support for bidirectional streaming (useful for control plane communication)
    • Protocol-level compression and HTTP/2 support
  • Justification: CDC systems require high throughput, low latency, and real-time processing capabilities. gRPC's binary protocol and streaming support make it ideal for continuous data change monitoring.

Complete Endpoint Definitions

MethodPathDescriptionAuth
SubscribeToChanges/cdc.v1.ChangeCaptureService/SubscribeToChangesEstablishes a bidirectional stream for real-time change eventsJWT + RBAC
GetChangeHistory/cdc.v1.ChangeCaptureService/GetChangeHistoryRetrieves historical changes within a time rangeJWT + RBAC
RegisterSource/cdc.v1.ChangeCaptureService/RegisterSourceRegisters a new data source for change captureJWT + Admin Role
UnregisterSource/cdc.v1.ChangeCaptureService/UnregisterSourceUnregisters a data source from change captureJWT + Admin Role
GetSourceStatus/cdc.v1.ChangeCaptureService/GetSourceStatusGets current status of a registered sourceJWT + RBAC
PauseCapture/cdc.v1.ChangeCaptureService/PauseCaptureTemporarily pauses change capture for a sourceJWT + Admin Role
ResumeCapture/cdc.v1.ChangeCaptureService/ResumeCaptureResumes change capture for a sourceJWT + Admin Role

Request and Response Schemas

SubscribeToChanges Request:

message SubscribeToChangesRequest {
  string source_id = 1;
  int64 start_timestamp = 2;
  int64 end_timestamp = 3;
  repeated string event_types = 4; // CREATE, UPDATE, DELETE
}

SubscribeToChanges Response (Stream):

message ChangeEvent {
  string event_id = 1;
  string source_id = 2;
  string entity_type = 3;
  string operation_type = 4; // CREATE, UPDATE, DELETE
  google.protobuf.Struct payload = 5;
  int64 timestamp = 6;
  string transaction_id = 7;
  string change_sequence = 8;
}

GetChangeHistory Request:

message GetChangeHistoryRequest {
  string source_id = 1;
  int64 start_timestamp = 2;
  int64 end_timestamp = 3;
  int32 page_size = 4;
  string page_token = 5;
}

GetChangeHistory Response:

message GetChangeHistoryResponse {
  repeated ChangeEvent events = 1;
  string next_page_token = 2;
}

RegisterSource Request:

message RegisterSourceRequest {
  string source_id = 1;
  string name = 2;
  string type = 3; // DATABASE, FILE, API
  SourceConfig config = 4;
}

RegisterSource Response:

message RegisterSourceResponse {
  string source_id = 1;
  bool success = 2;
  string message = 3;
}

HTTP Status Codes and Error Response Format

HTTP CodeDescription
200Success
400Bad Request (malformed request, validation errors)
401Unauthorized (missing or invalid auth)
403Forbidden (insufficient permissions)
429Rate Limited
500Internal Server Error
503Service Unavailable

Standardized error response:

{
  "error": {
    "code": "INVALID_ARGUMENT",
    "message": "Source ID is required",
    "details": [
      {
        "type": "google.rpc.BadRequest",
        "field_violations": [
          {
            "field": "source_id",
            "description": "Source ID is required"
          }
        ]
      }
    ]
  }
}

API Versioning Strategy

Version v1 will be the initial stable version with:

  • Semantic versioning: cdc.v1.*
  • Backward compatibility maintained for all methods
  • Breaking changes will be introduced in v2 with clear migration path

Pagination Design

Cursor-based pagination selected for the following reasons:

  1. Consistent performance: Cursor-based pagination provides stable performance regardless of data size
  2. Handles concurrent writes: Unlike offset-based approaches, cursor-based pagination is not affected by data changes during pagination
  3. Better for time-series data: CDC events are naturally ordered by timestamp, making cursor-based pagination ideal
  4. Simpler implementation: No need to handle complex offset calculations

Authentication and Authorization

Authentication:

  • JWT tokens for service-to-service authentication
  • OAuth2 for external client integration (if applicable)
  • API keys for simple integrations

Authorization:

  • RBAC model with roles:
    • ADMIN: Full access to all sources and operations
    • READER: Read-only access to change events
    • WRITER: Can register sources and manage capture state
  • Resource-based permissions (per-source access control)

Rate Limiting

Rate limits per endpoint:

  • SubscribeToChanges: 1000 requests/minute (per client)
  • GetChangeHistory: 500 requests/minute (per client)
  • RegisterSource: 100 requests/minute (per client)
  • UnregisterSource: 100 requests/minute (per client)

Enforcement strategy:

  • Token bucket algorithm with sliding window
  • Distributed rate limiting using Redis or similar
  • Client-side retry with exponential backoff

Idempotency Design

Idempotency key strategy:

  • For mutation endpoints (RegisterSource, UnregisterSource):
    • Client provides idempotency_key in request header
    • Server stores operation result by key for 24 hours
    • If same key is used, return cached result instead of reprocessing
// Example idempotency handling in gRPC service
public RegisterSourceResponse registerSource(
    RegisterSourceRequest request, 
    ServerCallStreamObserver<RegisterSourceResponse> responseObserver) {
    
    String idempotencyKey = request.getHeaders().get("idempotency-key");
    
    if (idempotencyKey != null) {
        // Check if operation was already processed
        RegisterSourceResponse cached = idempotencyCache.get(idempotencyKey);
        if (cached != null) {
            responseObserver.onNext(cached);
            responseObserver.onCompleted();
            return;
        }
    }
    
    // Process the request...
    RegisterSourceResponse response = processRequest(request);
    
    if (idempotencyKey != null) {
        idempotencyCache.put(idempotencyKey, response);
    }
    
    responseObserver.onNext(response);
    responseObserver.onCompleted();
}

3. Data Model Design

Entity-Relationship Diagram

erDiagram
    CHANGE_EVENT {
        string id PK
        string source_table
        string operation_type
        jsonb payload
        jsonb old_values
        timestamp created_at
        timestamp processed_at
        string status
        string error_message
        string processor_id
    }

    CHANGE_EVENT_PARTITION {
        string id PK
        string partition_key
        integer partition_number
        timestamp created_at
        timestamp last_processed_at
        string status
    }

    CHANGE_EVENT_PROCESSOR {
        string id PK
        string name
        string status
        timestamp last_heartbeat
        integer max_concurrent_events
        timestamp created_at
    }

    CHANGE_EVENT_TAG {
        string event_id FK
        string tag_name
    }

    TAG {
        string name PK
        string description
        timestamp created_at
    }

    CHANGE_EVENT --> CHANGE_EVENT_PARTITION : belongs_to
    CHANGE_EVENT --> CHANGE_EVENT_PROCESSOR : processed_by
    CHANGE_EVENT --> CHANGE_EVENT_TAG : has_tag
    CHANGE_EVENT_TAG --> TAG : tag_ref

Table / Collection Schema Definitions

-- Change events table with sharding support
CREATE TABLE change_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    source_table VARCHAR(255) NOT NULL,
    operation_type VARCHAR(10) NOT NULL CHECK (operation_type IN ('INSERT', 'UPDATE', 'DELETE')),
    payload JSONB NOT NULL,
    old_values JSONB,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    processed_at TIMESTAMP WITH TIME ZONE,
    status VARCHAR(20) DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'PROCESSING', 'SUCCESS', 'FAILED')),
    error_message TEXT,
    processor_id UUID REFERENCES change_event_processors(id),
    partition_key VARCHAR(255) NOT NULL,
    
    -- Composite index for query performance
    INDEX idx_change_events_source_table_created_at (source_table, created_at),
    INDEX idx_change_events_status_created_at (status, created_at),
    INDEX idx_change_events_partition_key (partition_key),
    INDEX idx_change_events_processor_id (processor_id)
);

-- Change event processors table
CREATE TABLE change_event_processors (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL UNIQUE,
    status VARCHAR(20) DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE', 'PAUSED')),
    last_heartbeat TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    max_concurrent_events INTEGER DEFAULT 10,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    INDEX idx_processors_status (status),
    INDEX idx_processors_last_heartbeat (last_heartbeat)
);

-- Change event partitions table
CREATE TABLE change_event_partitions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    partition_key VARCHAR(255) NOT NULL UNIQUE,
    partition_number INTEGER NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    last_processed_at TIMESTAMP WITH TIME ZONE,
    status VARCHAR(20) DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
    
    INDEX idx_partitions_partition_key (partition_key),
    INDEX idx_partitions_status (status)
);

-- Change event tags table
CREATE TABLE change_event_tags (
    event_id UUID REFERENCES change_events(id) ON DELETE CASCADE,
    tag_name VARCHAR(255) NOT NULL,
    
    PRIMARY KEY (event_id, tag_name),
    INDEX idx_tags_tag_name (tag_name)
);

-- Tags metadata table
CREATE TABLE tags (
    name VARCHAR(255) PRIMARY KEY,
    description TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

Primary Key Strategy

UUID Strategy: Using UUIDs as primary keys for the following reasons:

  • Scalability: No need to coordinate across shards or databases
  • Distribution: UUIDs can be generated in any order without conflicts
  • Decoupling: Event processors can process events independently without coordination
  • No Hotspots: Unlike auto-increment IDs, UUIDs don't create hotspots in distributed systems

Index Design

  1. Primary Indexes:

    • idx_change_events_source_table_created_at: For filtering by source table and time range
    • idx_change_events_status_created_at: For status-based queries and monitoring
    • idx_change_events_partition_key: For partition-based event retrieval
    • idx_change_events_processor_id: For processor-specific event queries
  2. Secondary Indexes:

    • idx_processors_status: For processor status monitoring
    • idx_partitions_partition_key: For partition lookups by key

Data Partitioning / Sharding Strategy

Sharding by Partition Key:

  • Events are sharded by partition_key field which represents the logical grouping (e.g., tenant_id, table_name)
  • Each partition is assigned to a specific processor instance
  • Partition number is calculated using consistent hashing or modulo operation
  • This ensures even distribution and allows for horizontal scaling

Soft Delete vs. Hard Delete Decision

Soft Delete: Events are soft-deleted with a status field rather than physical deletion. This decision is made because:

  • Audit Trail: Maintains complete history for compliance and debugging
  • Reprocessing Capability: Allows reprocessing failed events without data loss
  • Monitoring: Enables tracking of event lifecycle and performance metrics
  • Recovery: Easier to recover from data corruption or accidental deletions

Audit Trail Design

All changes to the system are audited with:

  • created_at: Timestamp of event creation
  • processed_at: When the event was processed (nullable)
  • error_message: For failed events
  • processor_id: Which processor handled the event

Data Archival Strategy and Retention Policy

Data TypeRetention PeriodArchive LocationReason
Change Events30 daysCold storage (S3)Compliance and debugging
ProcessorsIndefiniteDatabaseSystem metadata
TagsIndefiniteDatabaseConfiguration data

Archival process:

  • Events older than 30 days are moved to S3 with metadata preserved
  • Database entries are marked as archived with timestamp
  • Archive retention is handled by external storage lifecycle policies
// Example Java POJOs for data model representation

public class ChangeEvent {
    private UUID id;
    private String sourceTable;
    private String operationType;
    private Map<String, Object> payload;
    private Map<String, Object> oldValues;
    private LocalDateTime createdAt;
    private LocalDateTime processedAt;
    private String status;
    private String errorMessage;
    private UUID processorId;
    private String partitionKey;

    // Getters and setters
}

public class ChangeEventProcessor {
    private UUID id;
    private String name;
    private String status;
    private LocalDateTime lastHeartbeat;
    private Integer maxConcurrentEvents;
    private LocalDateTime createdAt;

    // Getters and setters
}

public class ChangeEventPartition {
    private UUID id;
    private String partitionKey;
    private Integer partitionNumber;
    private LocalDateTime createdAt;
    private LocalDateTime lastProcessedAt;
    private String status;

    // Getters and setters
}

4. Class Design & Service Layer

classDiagram
    class CDCProcessor {
        +processChanges()
        +handleSourceChange()
        +validateChange()
        +publishEvent()
        +getLatestCheckpoint()
    }
    
    class ChangeHandler {
        <<Interface>>
        +handleChange(ChangeEvent)
    }
    
    class MySQLChangeHandler {
        +handleChange(ChangeEvent)
        +extractRowData()
        +buildEventPayload()
    }
    
    class ChangeEvent {
        +id: UUID
        +source: String
        +operation: OperationType
        +table: String
        +before: Map~String, Object~
        +after: Map~String, Object~
        +timestamp: Instant
    }
    
    class ChangeEventPublisher {
        +publish(ChangeEvent)
        +serialize(ChangeEvent)
        +sendToKafka(ChangeEvent)
    }
    
    class ChangeEventValidator {
        +validate(ChangeEvent)
        +validateSchema()
        +validateConsistency()
    }
    
    class CheckpointManager {
        +saveCheckpoint(Checkpoint)
        +loadLatestCheckpoint()
        +updateProgress()
    }
    
    class Checkpoint {
        +sourceId: String
        +position: String
        +timestamp: Instant
    }
    
    class ChangeEventProcessor {
        +process(ChangeEvent)
        +applyTransformation()
        +handleError(ChangeEvent, Exception)
    }
    
    CDCProcessor --> ChangeHandler : delegatesTo
    ChangeHandler <|-- MySQLChangeHandler : implements
    CDCProcessor --> ChangeEventPublisher : publishesTo
    CDCProcessor --> ChangeEventValidator : validatesWith
    CDCProcessor --> CheckpointManager : managesCheckpoints
    ChangeEventPublisher --> ChangeEvent : serializes
    ChangeEventProcessor --> ChangeEvent : processes
    ChangeEvent --> Checkpoint : relatesTo
    
    class StateMachine {
        +currentState: State
        +handleEvent(Event)
        +transitionTo(State)
    }
    
    class State {
        +name: String
        +description: String
    }
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : change_detected
    Processing --> Idle : success
    Processing --> Error : failure
    Error --> Idle : retry_success
    Error --> Dead : max_retries_exceeded
    Dead --> [*] : permanent_failure
    
    state "Processing" {
        [*] --> Validating
        Validating --> Transforming : valid
        Validating --> Dead : invalid
        Transforming --> Publishing : transformed
        Publishing --> Idle : published
    }

Service Class Structure and Responsibilities

The CDC processor system consists of several core service classes:

  1. CDCProcessor: Main orchestrator that coordinates the end-to-end change processing pipeline
  2. ChangeHandler: Interface for handling different types of database changes (MySQL, PostgreSQL, etc.)
  3. MySQLChangeHandler: Concrete implementation for MySQL binlog events
  4. ChangeEventPublisher: Responsible for publishing processed events to message brokers
  5. ChangeEventValidator: Validates change events for consistency and schema compliance
  6. CheckpointManager: Manages checkpoint persistence for source position tracking

Interface / Abstract Class Design

public interface ChangeHandler {
    void handleChange(ChangeEvent changeEvent) throws Exception;
}

public abstract class ChangeEventProcessor {
    protected final ChangeEventValidator validator;
    protected final ChangeEventPublisher publisher;
    protected final CheckpointManager checkpointManager;
    
    public ChangeEventProcessor(ChangeEventValidator validator, 
                               ChangeEventPublisher publisher,
                               CheckpointManager checkpointManager) {
        this.validator = validator;
        this.publisher = publisher;
        this.checkpointManager = checkpointManager;
    }
    
    public abstract void process(ChangeEvent changeEvent) throws Exception;
}

Business Logic Encapsulation Patterns

The system uses the Strategy Pattern for handling different database types and the State Machine Pattern for managing processing states.

Critical-Path Method Implementation

public class MySQLChangeHandler implements ChangeHandler {
    private final ChangeEventProcessor processor;
    private final ObjectMapper objectMapper;
    private final EventPublisher eventPublisher;
    
    @Override
    public void handleChange(ChangeEvent changeEvent) throws Exception {
        // Transaction boundary - all operations within same transaction
        try (Transaction tx = transactionManager.begin()) {
            // Validate the change event
            if (!validator.validate(changeEvent)) {
                throw new ValidationException("Invalid change event: " + changeEvent.getId());
            }
            
            // Process the change - transform and enrich
            ChangeEvent processedEvent = processor.process(changeEvent);
            
            // Publish to message broker
            eventPublisher.publish(processedEvent);
            
            // Update checkpoint for source position tracking
            Checkpoint checkpoint = new Checkpoint(
                processedEvent.getSource(),
                getLatestPosition(),
                Instant.now()
            );
            checkpointManager.saveCheckpoint(checkpoint);
            
            // Commit transaction
            tx.commit();
        } catch (Exception e) {
            // Rollback on failure
            throw new ProcessingException("Failed to process change event: " + changeEvent.getId(), e);
        }
    }
    
    private String getLatestPosition() {
        // Implementation depends on source type (MySQL binlog position, etc.)
        return "mysql-bin.000001:12345";
    }
}

Transaction Boundary Design

Each change event processing operation is wrapped in a single database transaction that includes:

  1. Validation of the change event
  2. Transformation and enrichment of the event data
  3. Publishing to message broker (if using outbox pattern, this would be in the same transaction)
  4. Checkpoint persistence for source position tracking

Service Interface Contracts

public interface CDCProcessorService {
    void processChanges(List<ChangeEvent> changes) throws Exception;
    Checkpoint getLatestCheckpoint(String sourceId) throws Exception;
    void handleSourceChange(ChangeEvent changeEvent) throws Exception;
    boolean validateChange(ChangeEvent changeEvent) throws Exception;
}

Saga / Orchestration Pattern

For distributed transactions involving multiple systems, the system uses a saga pattern with compensating actions:

public class ChangeEventSaga {
    private final List<SagaStep> steps;
    
    public void execute(ChangeEvent changeEvent) {
        for (SagaStep step : steps) {
            try {
                step.execute(changeEvent);
            } catch (Exception e) {
                compensate(steps, step);
                throw new SagaExecutionException("Saga failed at step: " + step.getName(), e);
            }
        }
    }
    
    private void compensate(List<SagaStep> steps, SagaStep failedStep) {
        // Reverse the effects of completed steps
        for (int i = steps.indexOf(failedStep) - 1; i >= 0; i--) {
            steps.get(i).compensate();
        }
    }
}

Domain Object / Value Object Design

public class ChangeEvent {
    private final UUID id;
    private final String source;
    private final OperationType operation;
    private final String table;
    private final Map<String, Object> before;
    private final Map<String, Object> after;
    private final Instant timestamp;
    
    // Constructor, getters, equals, hashCode
}

public enum OperationType {
    INSERT, UPDATE, DELETE, TRUNCATE
}

public class Checkpoint {
    private final String sourceId;
    private final String position;
    private final Instant timestamp;
    
    // Constructor, getters
}

Implementation Details

The ChangeEventProcessor class implements the core business logic with a strategy pattern for different database types:

public class MySQLChangeHandler extends ChangeEventProcessor {
    private final ObjectMapper objectMapper;
    
    public MySQLChangeHandler(ChangeEventValidator validator,
                             ChangeEventPublisher publisher,
                             CheckpointManager checkpointManager) {
        super(validator, publisher, checkpointManager);
        this.objectMapper = new ObjectMapper();
    }
    
    @Override
    public void process(ChangeEvent changeEvent) throws Exception {
        // Apply transformations specific to MySQL changes
        ChangeEvent transformed = transformMySQLChange(changeEvent);
        
        // Validate the transformed event
        if (!validator.validate(transformed)) {
            throw new ValidationException("Transformed event failed validation");
        }
        
        // Publish to message broker
        publisher.publish(transformed);
    }
    
    private ChangeEvent transformMySQLChange(ChangeEvent changeEvent) {
        // Transform MySQL-specific fields to standardized format
        return new ChangeEvent(
            changeEvent.getId(),
            changeEvent.getSource(),
            changeEvent.getOperation(),
            changeEvent.getTable(),
            transformRowData(changeEvent.getBefore()),
            transformRowData(changeEvent.getAfter()),
            changeEvent.getTimestamp()
        );
    }
    
    private Map<String, Object> transformRowData(Map<String, Object> rowData) {
        // Handle MySQL-specific data types and convert to standard format
        Map<String, Object> transformed = new HashMap<>();
        for (Map.Entry<String, Object> entry : rowData.entrySet()) {
            transformed.put(entry.getKey(), convertMySQLType(entry.getValue()));
        }
        return transformed;
    }
    
    private Object convertMySQLType(Object value) {
        // Convert MySQL-specific types to standard Java types
        if (value instanceof java.sql.Timestamp) {
            return ((java.sql.Timestamp) value).toInstant();
        }
        if (value instanceof java.sql.Date) {
            return ((java.sql.Date) value).toLocalDate();
        }
        return value;
    }
}

5. Concurrency & Thread Safety

Concurrency Model

The Change Data Capture (CDC) processor will operate in a multi-threaded environment with the following concurrency model:

  • Thread pool executor for processing change events from multiple sources
  • Single-threaded consumers per database source to ensure ordered processing
  • Async I/O operations using Reactor pattern for non-blocking database polling and event publishing
  • Shared mutable state managed through thread-safe collections and atomic operations

Race Condition Prevention Strategy

Race conditions in CDC are primarily mitigated through:

  1. Database-level locking during snapshot and log reading operations
  2. Version-based conflict detection using row versioning or timestamps
  3. Idempotency checks in event processing to prevent duplicate handling
  4. State synchronization using read-write locks for shared state management

Optimistic vs. Pessimistic Locking Selection

Optimistic locking is selected for the following reasons:

  • Low contention scenario: CDC typically processes events in batches with minimal concurrent writes to the same rows
  • Better throughput: Avoids blocking operations that would slow down overall processing
  • Eventual consistency model: Accepts that conflicts can occur and handles them at the application level
  • Database compatibility: Most modern databases support optimistic locking through version fields or timestamps

Deadlock Prevention Strategy

Deadlock prevention mechanisms include:

  1. Consistent lock ordering: All threads acquire locks in the same order (e.g., by database name, then table name)
  2. Timeout-based acquisition: Maximum wait time of 5 seconds for any lock acquisition
  3. Deadlock detection cycle: Periodic check every 30 seconds to detect and break cycles
  4. Transaction size limitation: Batch processing of events to keep transactions small and short-lived

Idempotency Implementation for Concurrent Duplicate Requests

Idempotency is implemented through:

  1. Event ID tracking: Each processed event has a unique identifier stored in a deduplication table
  2. Idempotency key strategy: For mutations, use a composite key (source_id + operation_type + primary_key)
  3. Duplicate detection: Before processing, check if event already exists in deduplication store
  4. Stateful tracking: Use Redis-based distributed cache for fast duplicate detection with TTL of 24 hours
public class ChangeEventProcessor {
    private final Set<String> processedEventIds = new ConcurrentHashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    
    public boolean processEvent(ChangeEvent event) {
        String eventId = generateEventId(event);
        
        // Check if already processed (optimistic idempotency)
        if (processedEventIds.contains(eventId)) {
            return true; // Already processed, no-op
        }
        
        // Acquire write lock for processing
        lock.writeLock().lock();
        try {
            if (processedEventIds.contains(eventId)) {
                return true; // Double-checked locking
            }
            
            // Process the event
            processChange(event);
            
            // Mark as processed
            processedEventIds.add(eventId);
            
            // Cleanup old entries (LRU-like behavior)
            cleanupOldEntries();
            
            return true;
        } finally {
            lock.writeLock().unlock();
        }
    }
    
    private void cleanupOldEntries() {
        // Remove entries older than 24 hours
        long cutoffTime = System.currentTimeMillis() - (24 * 60 * 60 * 1000L);
        processedEventIds.removeIf(id -> {
            // Assuming event ID contains timestamp or can be parsed
            return extractTimestamp(id) < cutoffTime;
        });
    }
}

6. Sequence Diagrams for Key Flows

Happy Path Sequence Diagram

sequenceDiagram
    participant CDCProcessor
    participant Database
    participant MessageBroker
    participant Consumer

    CDCProcessor->>Database: Poll for changes (CDC)
    Database-->>CDCProcessor: Change events
    CDCProcessor->>MessageBroker: Publish change event
    MessageBroker-->>Consumer: Deliver event
    Consumer->>Consumer: Process event and update sink

Error / Edge Case Sequence Diagram

sequenceDiagram
    participant CDCProcessor
    participant Database
    participant MessageBroker
    participant DLQ

    CDCProcessor->>Database: Poll for changes (CDC)
    Database-->>CDCProcessor: Change event with invalid data
    CDCProcessor->>MessageBroker: Publish to DLQ
    MessageBroker-->>DLQ: Store poison message
    CDCProcessor->>CDCProcessor: Log error and alert SRE team

Async Flow Sequence Diagram

sequenceDiagram
    participant CDCProcessor
    participant Database
    participant MessageBroker
    participant Consumer
    participant Sink

    CDCProcessor->>Database: Poll for changes (CDC)
    Database-->>CDCProcessor: Change event
    CDCProcessor->>MessageBroker: Publish to topic
    MessageBroker-->>Consumer: Deliver event
    Consumer->>Sink: Apply change to destination system
    Sink-->>Consumer: Acknowledge success
    Consumer->>MessageBroker: Acknowledge event processing

7. Caching Design

Cache Strategy Selection

For Change Data Capture (CDC) processor, we'll use a cache-aside pattern with write-through behavior for critical operational data. This approach provides the best balance between performance and consistency for CDC operations where data freshness is paramount.

Cache Key Design

Cache keys will follow a structured namespace pattern:

cdc:processor:{sourceId}:{entityType}:{entityId}
cdc:processor:metadata:{sourceId}:{entityType}

Example key structure:

String cacheKey = String.format("cdc:processor:%s:%s:%s", 
    sourceId, entityType, entityId);

TTL Strategy

Data TypeTTLReason
Change Events5 minutesRecent changes need to be available for processing
Source Metadata1 hourConfiguration rarely changes but needs to be fresh
Schema Registry Cache24 hoursSchema definitions are stable and expensive to fetch
Processing State10 minutesIn-flight processing state should not persist too long

Cache Eviction Policy

We'll use LRU (Least Recently Used) eviction policy with a maximum size of 100,000 entries to prevent memory bloat. This ensures that hot data stays in cache while stale entries are automatically evicted.

Cache Stampede Prevention

To prevent cache stampedes:

  1. Probabilistic early expiry: Set TTL to 75% of configured value (e.g., 3.75 minutes for 5-minute TTL)
  2. Distributed locks: Use Redis distributed locks when cache misses occur for the same key
  3. Cache warming: Pre-populate frequently accessed change events during system startup

Distributed Cache Architecture

We'll use Redis Cluster with:

  • 3 master nodes and 3 replica nodes for high availability
  • 100% automatic failover capability
  • 64-bit hash slots for consistent hashing
  • Redis Sentinel monitoring for automatic node recovery

Cache Invalidation Strategy

We'll implement event-driven cache invalidation:

  1. When a change event is processed, invalidate the corresponding cached entity
  2. Use Redis Pub/Sub to broadcast invalidation messages across the cluster
  3. Implement cache warming for frequently accessed entities when they're invalidated
// Example cache invalidation logic in CDC processor
public void invalidateCachedEntity(String sourceId, String entityType, String entityId) {
    String cacheKey = String.format("cdc:processor:%s:%s:%s", sourceId, entityType, entityId);
    redisTemplate.delete(cacheKey);
    
    // Broadcast invalidation event to other nodes
    String invalidateEvent = String.format("invalidate:%s:%s", entityType, entityId);
    redisTemplate.convertAndSend("cdc-cache-invalidation", invalidateEvent);
}

Cache Read-Through Pattern

public ChangeEvent getCachedChangeEvent(String sourceId, String entityType, String entityId) {
    String cacheKey = String.format("cdc:processor:%s:%s:%s", sourceId, entityType, entityId);
    
    // Try to get from cache
    ChangeEvent cachedEvent = (ChangeEvent) redisTemplate.opsForValue().get(cacheKey);
    
    if (cachedEvent != null) {
        return cachedEvent;
    }
    
    // Cache miss - acquire distributed lock to prevent stampede
    String lockKey = cacheKey + ":lock";
    if (redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", Duration.ofSeconds(10))) {
        try {
            // Double-check cache after lock acquisition
            ChangeEvent freshEvent = (ChangeEvent) redisTemplate.opsForValue().get(cacheKey);
            if (freshEvent != null) {
                return freshEvent;
            }
            
            // Fetch from database and cache
            ChangeEvent event = fetchFromDatabase(sourceId, entityType, entityId);
            redisTemplate.opsForValue().set(cacheKey, event, Duration.ofMinutes(5));
            return event;
        } finally {
            // Release lock
            redisTemplate.delete(lockKey);
        }
    } else {
        // Wait briefly and retry
        Thread.sleep(50);
        return getCachedChangeEvent(sourceId, entityType, entityId);
    }
}

8. Repository / Data Access Layer

Repository Pattern Implementation

The repository pattern provides a clean abstraction between domain logic and data persistence, supporting testability and decoupling of data access concerns from business logic.

public interface ChangeEventRepository {
    void save(ChangeEvent event);
    Optional<ChangeEvent> findById(String id);
    List<ChangeEvent> findBySourceAndTimestampRange(
        String source, 
        Instant startTime, 
        Instant endTime,
        Pageable pageable
    );
    long countBySourceAndTimestampRange(String source, Instant startTime, Instant endTime);
    void deleteById(String id);
    void deleteBySourceAndTimestampRange(String source, Instant startTime, Instant endTime);
}

@Repository
public class ChangeEventRepositoryImpl implements ChangeEventRepository {
    private final JdbcTemplate jdbcTemplate;
    private final ObjectMapper objectMapper;
    
    public ChangeEventRepositoryImpl(JdbcTemplate jdbcTemplate, ObjectMapper objectMapper) {
        this.jdbcTemplate = jdbcTemplate;
        this.objectMapper = objectMapper;
    }
    
    @Override
    public void save(ChangeEvent event) {
        String sql = """
            INSERT INTO change_events (
                id, source, operation, table_name, 
                before_data, after_data, timestamp, 
                transaction_id, metadata
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """;
            
        jdbcTemplate.update(sql, 
            event.getId(),
            event.getSource(),
            event.getOperation().name(),
            event.getTableName(),
            event.getBeforeData() != null ? 
                objectMapper.writeValueAsString(event.getBeforeData()) : null,
            event.getAfterData() != null ? 
                objectMapper.writeValueAsString(event.getAfterData()) : null,
            event.getTimestamp(),
            event.getTransactionId(),
            event.getMetadata() != null ? 
                objectMapper.writeValueAsString(event.getMetadata()) : null
        );
    }
    
    @Override
    public Optional<ChangeEvent> findById(String id) {
        String sql = "SELECT * FROM change_events WHERE id = ?";
        try {
            return Optional.of(jdbcTemplate.queryForObject(sql, new ChangeEventRowMapper(), id));
        } catch (EmptyResultDataAccessException e) {
            return Optional.empty();
        }
    }
    
    @Override
    public List<ChangeEvent> findBySourceAndTimestampRange(
        String source, 
        Instant startTime, 
        Instant endTime,
        Pageable pageable
    ) {
        String sql = """
            SELECT * FROM change_events 
            WHERE source = ? AND timestamp BETWEEN ? AND ?
            ORDER BY timestamp ASC
            LIMIT ? OFFSET ?
            """;
            
        return jdbcTemplate.query(sql, 
            new ChangeEventRowMapper(),
            source,
            startTime,
            endTime,
            pageable.getPageSize(),
            pageable.getOffset()
        );
    }
    
    @Override
    public long countBySourceAndTimestampRange(String source, Instant startTime, Instant endTime) {
        String sql = "SELECT COUNT(*) FROM change_events WHERE source = ? AND timestamp BETWEEN ? AND ?";
        return jdbcTemplate.queryForObject(sql, Long.class, source, startTime, endTime);
    }
    
    @Override
    public void deleteById(String id) {
        String sql = "DELETE FROM change_events WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
    
    @Override
    public void deleteBySourceAndTimestampRange(String source, Instant startTime, Instant endTime) {
        String sql = "DELETE FROM change_events WHERE source = ? AND timestamp BETWEEN ? AND ?";
        jdbcTemplate.update(sql, source, startTime, endTime);
    }
}

ORM vs. Raw Query Decisions

For the Change Data Capture system, we use raw JDBC queries with JdbcTemplate for several reasons:

  1. Performance: Raw SQL provides better performance than ORM-generated queries, especially for bulk operations and complex filtering
  2. Control: Direct control over query execution and optimization
  3. Flexibility: Ability to implement custom index usage and query hints
  4. Simplicity: Avoids ORM complexity for a straightforward data model

Read vs. Write Separation

We implement read-write separation using the CQRS pattern for optimal performance:

public interface ChangeEventReader {
    List<ChangeEvent> findRecentEvents(String source, int limit);
    Optional<ChangeEvent> findByTransactionId(String transactionId);
    List<ChangeEvent> findEventsByOperationAndTable(
        String operation, 
        String tableName,
        Instant startTime,
        Instant endTime
    );
}

public interface ChangeEventWriter {
    void save(ChangeEvent event);
    void deleteEventsBefore(Instant timestamp);
}

@Service
public class ChangeEventService {
    private final ChangeEventReader reader;
    private final ChangeEventWriter writer;
    
    public ChangeEventService(ChangeEventReader reader, ChangeEventWriter writer) {
        this.reader = reader;
        this.writer = writer;
    }
    
    public List<ChangeEvent> getRecentEvents(String source, int limit) {
        return reader.findRecentEvents(source, limit);
    }
    
    public void processChange(ChangeEvent event) {
        writer.save(event);
    }
}

Connection Pool Configuration

Connection pool is configured with optimal settings for high-throughput CDC processing:

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

N+1 Query Prevention Strategy

We prevent N+1 queries by implementing batch operations and eager loading:

public class BatchChangeEventProcessor {
    private final ChangeEventRepository repository;
    
    public void processBatch(List<ChangeEvent> events) {
        // Batch insert instead of individual saves
        String sql = """
            INSERT INTO change_events (
                id, source, operation, table_name, 
                before_data, after_data, timestamp, 
                transaction_id, metadata
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """;
            
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ChangeEvent event = events.get(i);
                ps.setString(1, event.getId());
                ps.setString(2, event.getSource());
                ps.setString(3, event.getOperation().name());
                ps.setString(4, event.getTableName());
                ps.setObject(5, event.getBeforeData(), Types.JSON);
                ps.setObject(6, event.getAfterData(), Types.JSON);
                ps.setTimestamp(7, Timestamp.from(event.getTimestamp()));
                ps.setString(8, event.getTransactionId());
                ps.setObject(9, event.getMetadata(), Types.JSON);
            }
            
            @Override
            public int getBatchSize() {
                return events.size();
            }
        });
    }
}

Batch Operation Design

Batch operations are designed to handle high-volume data processing efficiently:

public class ChangeEventBatchProcessor {
    private static final int BATCH_SIZE = 1000;
    
    public void processEventsInBatches(List<ChangeEvent> events) {
        for (int i = 0; i < events.size(); i += BATCH_SIZE) {
            int end = Math.min(i + BATCH_SIZE, events.size());
            List<ChangeEvent> batch = events.subList(i, end);
            
            try {
                processBatch(batch);
                // Commit batch to database
                transactionManager.commit();
            } catch (Exception e) {
                // Handle partial failure and retry logic
                handleBatchFailure(batch, e);
            }
        }
    }
    
    private void processBatch(List<ChangeEvent> batch) {
        // Implementation of batch processing with proper error handling
    }
    
    private void handleBatchFailure(List<ChangeEvent> failedBatch, Exception cause) {
        // Log failed batch and potentially send to dead letter queue
        log.error("Failed to process batch of {} events", failedBatch.size(), cause);
    }
}

Data Access Layer Testing Strategy

@ExtendWith(MockitoExtension.class)
public class ChangeEventRepositoryImplTest {
    @Mock
    private JdbcTemplate jdbcTemplate;
    
    @Mock
    private ObjectMapper objectMapper;
    
    private ChangeEventRepositoryImpl repository;
    
    @BeforeEach
    void setUp() {
        repository = new ChangeEventRepositoryImpl(jdbcTemplate, objectMapper);
    }
    
    @Test
    void shouldSaveChangeEvent() {
        // Given
        ChangeEvent event = createSampleEvent();
        
        // When
        repository.save(event);
        
        // Then
        verify(jdbcTemplate).update(anyString(), any());
    }
    
    @Test
    void shouldFindById() {
        // Given
        ChangeEvent event = createSampleEvent();
        when(jdbcTemplate.queryForObject(anyString(), any(), any()))
            .thenReturn(event);
        
        // When
        Optional<ChangeEvent> result = repository.findById("test-id");
        
        // Then
        assertThat(result).isPresent();
    }
    
    private ChangeEvent createSampleEvent() {
        return ChangeEvent.builder()
            .id("test-id")
            .source("test-source")
            .operation(Operation.INSERT)
            .tableName("users")
            .timestamp(Instant.now())
            .build();
    }
}

9. Asynchronous Processing & Messaging

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

Change Data Capture (CDC) is fundamentally an asynchronous data processing pipeline. The core decision is to treat database change events as the primary trigger for downstream processing, rather than blocking on every write operation.

Synchronous operations:

  • Database write operations (INSERT/UPDATE/DELETE) - These must complete successfully before the transaction commits to ensure data consistency and atomicity.

Asynchronous operations:

  • Change event publishing to message broker - This happens after successful database commit, allowing the application to continue without waiting for external systems.
  • Data transformation and enrichment - These can be performed asynchronously once the raw change event is available.
  • External system notifications (e.g., webhooks, analytics) - These are decoupled from the primary transaction flow to avoid performance degradation and improve system resilience.

The reason for this separation is that CDC systems must be highly available and fault-tolerant. By decoupling the write operation from downstream processing, we ensure that a failure in one component doesn't block the entire database transaction.

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

We'll use JSON Schema for its simplicity and wide adoption in event-driven systems, with a versioning strategy based on semantic versioning (e.g., v1, v2) to support backward compatibility.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "CDC Event",
  "version": "1.0.0",
  "type": "object",
  "properties": {
    "eventId": {
      "type": "string",
      "description": "Unique identifier for this event"
    },
    "source": {
      "type": "string",
      "description": "Database source identifier"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the event occurred"
    },
    "operation": {
      "type": "string",
      "enum": ["INSERT", "UPDATE", "DELETE"],
      "description": "Type of database operation"
    },
    "table": {
      "type": "string",
      "description": "Name of the database table"
    },
    "primaryKey": {
      "type": "object",
      "description": "Primary key values of the changed record"
    },
    "before": {
      "type": "object",
      "description": "Record state before the operation (for UPDATE/DELETE)"
    },
    "after": {
      "type": "object",
      "description": "Record state after the operation (for INSERT/UPDATE)"
    },
    "metadata": {
      "type": "object",
      "description": "Additional metadata about the event"
    }
  },
  "required": ["eventId", "source", "timestamp", "operation", "table"]
}

Versioning strategy:

  • Schema version is included in the message header or as a field within the payload
  • When schema changes, new versioned topics are created (e.g., cdc-events-v1, cdc-events-v2)
  • Consumers can migrate to newer versions at their own pace

Dead letter queue strategy and poison message handling

Poison messages are those that fail repeatedly during processing, potentially causing system degradation or blocking other messages. Our strategy includes:

  1. Dead Letter Queue (DLQ) Configuration:

    • Each consumer has a dedicated DLQ topic for failed messages
    • Failed messages are moved to DLQ after reaching max retry limit (e.g., 5 attempts)
    • DLQ messages are stored with metadata indicating the original topic, error type, and last failure timestamp
  2. Poison Message Handling:

    • Messages that fail with non-retryable errors (e.g., invalid data format, malformed payload) are immediately sent to DLQ
    • Messages that fail due to transient issues (e.g., network timeout, rate limiting) are retried with exponential backoff
    • DLQ messages are periodically reviewed by system administrators to determine if they should be reprocessed or discarded
  3. Error Classification:

    • Retryable errors (network issues, temporary service unavailability): retry with exponential backoff
    • Non-retryable errors (data validation failures, malformed payloads): send to DLQ immediately
    • System errors (internal server errors, resource exhaustion): retry with exponential backoff but eventually send to DLQ

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

We choose at-least-once delivery for CDC events, with a strong emphasis on idempotency in downstream consumers.

Justification:

  • CDC systems are typically used for data synchronization, analytics, and audit trails where data consistency is more important than avoiding duplicates
  • At-least-once delivery provides better fault tolerance and ensures that no changes are missed during system failures
  • The cost of duplicate processing in most downstream systems is acceptable compared to the risk of missing data changes
  • Implementing exactly-once semantics would require complex coordination mechanisms (e.g., distributed transactions) that add significant complexity and potential performance overhead

For systems where exactly-once semantics are required, we recommend implementing idempotent processing at the consumer level.

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

public class RetryPolicy {
    private static final int MAX_RETRIES = 5;
    private static final long INITIAL_DELAY_MS = 1000;
    private static final double BACKOFF_MULTIPLIER = 2.0;
    private static final double JITTER_RANGE = 0.1; // 10% jitter

    public static long calculateDelay(int attempt) {
        if (attempt <= 0) return 0;
        
        long baseDelay = (long) (INITIAL_DELAY_MS * Math.pow(BACKOFF_MULTIPLIER, attempt - 1));
        long jitter = (long) (baseDelay * JITTER_RANGE * (Math.random() - 0.5) * 2);
        return baseDelay + jitter;
    }

    public static boolean shouldRetry(Exception exception) {
        // Non-retryable errors
        if (exception instanceof IllegalArgumentException || 
            exception instanceof ValidationException ||
            exception instanceof DataFormatException) {
            return false;
        }
        
        // Retryable errors
        return exception instanceof NetworkException ||
               exception instanceof TimeoutException ||
               exception instanceof ServiceUnavailableException;
    }
}

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

We do NOT use the outbox pattern in this design for the following reasons:

  1. Simpler Architecture: CDC systems often integrate with existing database change capture tools (like Debezium) that already provide reliable event publishing capabilities.

  2. Existing Transactional Guarantees: When using database CDC tools, the change events are typically published within the same transaction boundary as the database write, ensuring consistency.

  3. Reduced Complexity: The outbox pattern adds another layer of complexity and requires additional storage and processing overhead.

  4. Message Broker Integration: Modern message brokers like Kafka provide strong durability guarantees when properly configured with replication and retention policies.

However, if we were to implement the outbox pattern in a custom CDC system:

// Example of outbox table structure (not implemented here)
public class OutboxEvent {
    private UUID id;
    private String payload;
    private String status; // PENDING, PROCESSED, FAILED
    private LocalDateTime createdAt;
    private LocalDateTime processedAt;
}

Sequence diagram for all async flows (Mermaid)

sequenceDiagram
    participant DB as Database
    participant CDC as CDC Processor
    participant MQ as Message Broker
    participant ConsumerA as Consumer A
    participant ConsumerB as Consumer B

    DB->>CDC: Transaction Commit (INSERT/UPDATE/DELETE)
    CDC->>MQ: Publish Change Event
    MQ->>ConsumerA: Deliver Event
    ConsumerA->>MQ: Acknowledge Processing
    MQ->>ConsumerB: Deliver Event
    ConsumerB->>MQ: Acknowledge Processing

    note over CDC,MQ: Retry logic and DLQ handling for failed consumers
sequenceDiagram
    participant DB as Database
    participant CDC as CDC Processor
    participant MQ as Message Broker
    participant DLQ as Dead Letter Queue

    DB->>CDC: Transaction Commit (INSERT/UPDATE/DELETE)
    CDC->>MQ: Publish Change Event
    MQ->>ConsumerA: Deliver Event (Retry 1)
    ConsumerA-->>MQ: Processing Failed
    MQ->>ConsumerA: Deliver Event (Retry 2)
    ConsumerA-->>MQ: Processing Failed
    MQ->>DLQ: Move to DLQ (Max retries exceeded)

10. Error Handling Design

Error Classification Hierarchy

Errors in a CDC processor are categorized into three main types:

  1. Domain Errors: Business logic violations or data inconsistencies (e.g., invalid change event format, unsupported database operation)
  2. Infrastructure Errors: System-level issues (e.g., database connection failures, message broker unavailability)
  3. Validation Errors: Input validation issues (e.g., missing required fields, malformed payloads)
public enum ErrorType {
    VALIDATION_ERROR,
    DOMAIN_ERROR,
    INFRASTRUCTURE_ERROR
}

Error Propagation Strategy

Errors are handled at the service layer and propagated upward through well-defined exception hierarchies. For infrastructure errors, retries are attempted before bubbling up to higher layers.

Retry Strategy with Exponential Backoff and Jitter

Retry logic uses exponential backoff with jitter to prevent thundering herd:

public class RetryStrategy {
    private static final int MAX_RETRIES = 3;
    private static final long BASE_DELAY_MS = 1000;
    private static final double JITTER_RANGE = 0.5;

    public <T> T executeWithRetry(Supplier<T> operation, Predicate<Exception> shouldRetry) {
        int attempts = 0;
        while (attempts < MAX_RETRIES) {
            try {
                return operation.get();
            } catch (Exception e) {
                if (!shouldRetry.test(e) || attempts >= MAX_RETRIES - 1) {
                    throw new RetryableException("Operation failed after " + MAX_RETRIES + " attempts", e);
                }
                long delay = (long) (BASE_DELAY_MS * Math.pow(2, attempts) + 
                    (Math.random() - 0.5) * BASE_DELAY_MS * JITTER_RANGE);
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RetryableException("Retry interrupted", ie);
                }
                attempts++;
            }
        }
        throw new RetryableException("Max retries exceeded");
    }
}

Circuit Breaker Design

For external dependencies like message brokers or databases, a circuit breaker pattern is implemented:

public class CircuitBreaker {
    private final int failureThreshold;
    private final long timeoutMs;
    private final AtomicInteger failureCount = new AtomicInteger(0);
    private final AtomicLong lastFailureTime = new AtomicLong(0);
    private volatile CircuitState state = CircuitState.CLOSED;

    public enum CircuitState {
        CLOSED, OPEN, HALF_OPEN
    }

    public <T> T execute(Supplier<T> operation) throws Exception {
        switch (state) {
            case CLOSED:
                try {
                    T result = operation.get();
                    failureCount.set(0);
                    return result;
                } catch (Exception e) {
                    if (failureCount.incrementAndGet() >= failureThreshold) {
                        state = CircuitState.OPEN;
                        lastFailureTime.set(System.currentTimeMillis());
                    }
                    throw e;
                }

            case OPEN:
                if (System.currentTimeMillis() - lastFailureTime.get() > timeoutMs) {
                    state = CircuitState.HALF_OPEN;
                } else {
                    throw new CircuitBreakerOpenException("Circuit is open");
                }

            case HALF_OPEN:
                try {
                    T result = operation.get();
                    state = CircuitState.CLOSED;
                    failureCount.set(0);
                    return result;
                } catch (Exception e) {
                    state = CircuitState.OPEN;
                    lastFailureTime.set(System.currentTimeMillis());
                    throw e;
                }
        }
        throw new IllegalStateException("Invalid circuit state");
    }
}

Fallback Behavior Design

For critical dependencies, fallback mechanisms are implemented:

public class FallbackHandler {
    public void handleDatabaseFailure() {
        // Log the failure and potentially send to dead letter queue
        logger.warn("Database connection failed, using fallback mechanism");
    }

    public void handleMessageBrokerFailure() {
        // Retry with exponential backoff or queue to dead letter
        logger.error("Message broker unavailable, queuing event for retry");
    }
}

Error Logging Format and Alerting Thresholds

Structured logging includes trace context, error codes, and user/entity identifiers:

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

    public void logError(String traceId, String userId, String entityId, 
                        String errorCode, Exception e) {
        logger.error("Error in CDC processor",
            "trace_id", traceId,
            "user_id", userId,
            "entity_id", entityId,
            "error_code", errorCode,
            "message", e.getMessage(),
            "stack_trace", e.getStackTrace());
    }
}

Alerting thresholds:

  • Warning: 5% of total events fail
  • Critical: 20% of total events fail or circuit breaker opens
  • On-call escalation: When circuit breaker is open for >5 minutes

Error Handling in Retryable Scenarios

For retryable errors, the system uses a combination of:

  1. Idempotency keys to prevent duplicate processing
  2. Event versioning to handle schema evolution
  3. Dead letter queue (DLQ) for permanently failed events
public class ErrorHandlingService {
    private final DeadLetterQueue dlq;
    private final RetryStrategy retryStrategy;

    public void processEventWithRetry(ChangeEvent event) {
        try {
            retryStrategy.executeWithRetry(() -> processChange(event), 
                this::isRetryableError);
        } catch (RetryableException e) {
            // Move to DLQ for permanent failures
            dlq.enqueue(event);
            logger.error("Event moved to DLQ after retries exhausted", e);
        }
    }

    private boolean isRetryableError(Exception e) {
        return e instanceof DatabaseConnectionException || 
               e instanceof MessageBrokerUnavailableException;
    }
}

11. Security Design

Input Validation and Sanitization Strategy

All external inputs are validated using a combination of:

  • Apache Commons Validator for standard validation (email, URL, phone)
  • Custom regex patterns for domain-specific constraints
  • OWASP Java HTML Sanitizer for sanitizing user-generated content to prevent XSS attacks

SQL Injection Prevention

  • Prepared statements are used exclusively for all database queries
  • Parameterized queries with named parameters (e.g., SELECT * FROM users WHERE id = :userId)
  • No dynamic query construction from user input
  • Database user permissions restricted to minimum required privileges (e.g., read-only for read operations)

Authentication Middleware Design

  • JWT-based authentication with 2-hour expiration and 15-minute refresh window
  • OAuth2 integration for third-party identity providers (Google, GitHub)
  • Authentication interceptor that validates JWT tokens before service method execution
  • Token revocation endpoint to invalidate sessions during logout or security events

Authorization Enforcement

  • Role-Based Access Control (RBAC) with hierarchical roles:
    • ADMIN (full access)
    • OPERATOR (read/write on CDC streams)
    • VIEWER (read-only access to logs and status)
  • Permission checking at service layer using @PreAuthorize annotations or manual checks
  • Resource-based authorization where access is tied to specific CDC stream IDs

Sensitive Data Encryption

  • At rest: AES-256 encryption using AWS KMS for key management and rotation
  • In transit: TLS 1.3 with HSTS header enforcement for all API endpoints
  • Encryption keys: Managed through AWS Secrets Manager with automatic rotation every 90 days

PII Handling and Masking Strategy

  • PII data (user IDs, email addresses) are encrypted at rest using AES-256
  • Masking policy: PII fields in logs and responses are masked (e.g., user@example.com → u***@example.com)
  • Data classification tags applied to all fields for automated masking and compliance

Secrets Management

  • AWS Secrets Manager used for storing:
    • Database credentials (rotated every 90 days)
    • Third-party API keys (e.g., Kafka, Redis)
    • JWT signing keys
  • Secrets rotation automated via Lambda functions with audit logging

Audit Logging Design

  • Event types logged:
    • CDC_STREAM_CREATED, CDC_STREAM_MODIFIED, CDC_STREAM_DELETED
    • USER_LOGIN, USER_LOGOUT, PERMISSION_GRANTED
  • Log format:
{
  "timestamp": "2023-10-27T14:30:00Z",
  "trace_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "user_id": "user-123",
  "event_type": "CDC_STREAM_CREATED",
  "resource_id": "stream-456",
  "ip_address": "192.168.1.100",
  "user_agent": "Mozilla/5.0...",
  "details": {
    "stream_name": "user_events",
    "source_db": "postgres-1"
  }
}
  • Retention policy: Audit logs retained for 3 years with daily backups to S3 Glacier
  • Compliance: Logs are structured to support SOC2, GDPR, and HIPAA compliance reporting
// Example of input validation in a service method
public void createCDCStream(CDCStreamRequest request) {
    // Validate input using Apache Commons Validator
    if (!EmailValidator.getInstance().isValid(request.getOwnerEmail())) {
        throw new ValidationException("Invalid email address");
    }

    // Sanitize user input
    String sanitizedStreamName = HtmlSanitizer.sanitize(request.getStreamName());

    // Validate stream name format
    if (!sanitizedStreamName.matches("^[a-zA-Z0-9_-]+$")) {
        throw new ValidationException("Stream name contains invalid characters");
    }

    // Proceed with business logic...
}

12. Testing Strategy

Unit Testing Scope and Coverage Targets

Unit tests will cover 85%+ of business logic and service layer code paths. Focus areas include:

  • Service method validation with mock dependencies
  • Business logic boundary conditions and edge cases
  • Error handling paths in service methods
  • Repository method integration with in-memory databases
  • Event publisher behavior with mock event buses

Integration Testing Strategy

Database Integration Tests:

  • Use testcontainers for PostgreSQL/MySQL to validate actual query execution
  • Test transaction boundaries and concurrent access patterns
  • Validate schema migrations and data consistency across versions

External Service Integration Tests:

  • WireMock for simulating CDC source systems (e.g., Kafka, database change streams)
  • Test full end-to-end flows with real message brokers
  • Validate data transformation and routing logic

Cross-Service Integration Tests:

  • Embedded Redis for cache integration testing
  • Test event-driven workflows with real message queues (e.g., Kafka, RabbitMQ)
  • Validate saga orchestration and compensation logic

Contract Testing

Pact Broker Integration:

  • Define consumer-driven contracts for CDC processor API endpoints
  • Validate message format compatibility between producer and consumer services
  • Automate contract testing in CI pipeline with Pact Broker integration

Performance Testing Tool and Key Scenarios

Load Testing Framework:

  • Use k6 for load testing with realistic data volumes and throughput targets
  • Simulate concurrent CDC events from multiple database sources

Key Performance Scenarios:

  • High-volume event processing (10k+ events/sec)
  • Latency under concurrent load (p95 < 200ms for 1000 concurrent events)
  • Memory usage under sustained load (GC pressure < 5% of total runtime)
  • Throughput testing with various payload sizes (1KB to 10MB messages)

Test Data Management Strategy

Test Data Generation:

  • Factory pattern for generating realistic CDC event payloads
  • Use data builders to create valid and invalid test cases
  • Implement fixtures with pre-defined database states for integration tests

Test Data Seeding:

  • Use Liquibase or Flyway to manage test database schema versions
  • Seed test data with realistic distribution patterns for performance testing
  • Implement data cleanup strategies to ensure test isolation

Test Data Isolation:

  • Use database schemas per test environment (dev, staging, CI)
  • Implement transaction rollback in unit tests to maintain clean state
  • Use UUIDs for test entities to prevent cross-test contamination

Data Volume Management:

  • Generate synthetic data sets matching production scale (1M+ records)
  • Use data sampling techniques for performance testing with reduced datasets
  • Implement data aging strategies to simulate real-world data lifecycle

13. Observability Design

Structured Logging Schema

All logs must follow a consistent schema to enable effective search, filtering, and correlation across services:

{
  "timestamp": "2023-10-27T14:30:45.123Z",
  "level": "INFO",
  "service": "cdc-processor",
  "trace_id": "1234567890abcdef1234567890abcdef",
  "span_id": "abcdef1234567890",
  "user_id": "user-123",
  "entity_id": "change-456",
  "event_type": "CHANGE_EVENT_PROCESSED",
  "message": "Successfully processed change event for table users",
  "error_code": null,
  "error_details": null,
  "duration_ms": 150,
  "source_table": "users",
  "change_type": "UPDATE",
  "row_key": "user-123"
}

PII masking rules:

  • User IDs in logs are masked to user-XXXX
  • Email addresses are truncated to user@***.com
  • Full names are replaced with John Doe or similar generic placeholder

Distributed Tracing Instrumentation

Using OpenTelemetry for end-to-end tracing with custom spans:

// Custom span for CDC event processing pipeline
Span span = tracer.spanBuilder("process-cdc-event")
    .setAttribute("event.source", "mysql-binlog")
    .setAttribute("event.table", "users")
    .setAttribute("event.change_type", "UPDATE")
    .startSpan();

// Add custom attributes to each operation within the span
span.setAttribute("db.connection_id", connectionId);
span.setAttribute("message.offset", offset);

Key operations to trace:

  • process-cdc-event - Main event processing flow
  • validate-change-event - Input validation logic
  • transform-to-json - Data transformation steps
  • publish-event - Message publishing to Kafka
  • persist-metadata - Database metadata updates

Metrics Design

RED Method Metrics (Rate, Errors, Duration):

Metric NameTypeLabelsDescription
cdc_events_processed_totalCounterevent_type, table_name, statusTotal events processed
cdc_events_processing_duration_secondsHistogramevent_type, table_nameProcessing time per event
cdc_events_errors_totalCountererror_type, table_nameFailed events by type
cdc_event_queue_sizeGaugequeue_nameCurrent queue size
cdc_events_backlog_secondsHistogramtable_nameTime events spent in queue

Example metric labels:

cdc_events_processed_total{event_type="INSERT", table_name="users", status="success"} 123
cdc_events_processing_duration_seconds{event_type="UPDATE", table_name="orders", quantile="0.95"} 120

Health Check Endpoint Design

@RestController
@RequestMapping("/health")
public class HealthController {
    
    @GetMapping("/live")
    public ResponseEntity<Map<String, Object>> live() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "healthy");
        response.put("timestamp", Instant.now());
        response.put("service", "cdc-processor");
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/ready")
    public ResponseEntity<Map<String, Object>> ready() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "ready");
        response.put("timestamp", Instant.now());
        response.put("database_connected", dbHealthCheck());
        response.put("kafka_connected", kafkaHealthCheck());
        response.put("message_queue_size", queueSize());
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/startup")
    public ResponseEntity<Map<String, Object>> startup() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "startup_complete");
        response.put("timestamp", Instant.now());
        response.put("components", Arrays.asList("database", "kafka", "queue"));
        return ResponseEntity.ok(response);
    }
}

Alerting Thresholds

MetricWarning LevelCritical LevelEscalation
cdc_events_errors_total>5 errors/minute>20 errors/minuteOn-call engineer
cdc_events_processing_duration_seconds (p95)>200ms>500msOn-call engineer
cdc_event_queue_size>1000 events>5000 eventsOn-call engineer
cdc_events_backlog_seconds (p95)>30 seconds>60 secondsOn-call engineer
cdc_events_processed_total (rate)<100 events/sec<50 events/secOn-call engineer

Alerts should trigger with 1-minute delay to avoid flapping and include context such as:

  • Affected tables
  • Error types
  • Processing lag duration
  • Service instance ID

14. Open Questions, Risks & Trade-offs

Decisions requiring product / engineering alignment

  • CDC source system selection: Which database systems will be supported (PostgreSQL, MySQL, MongoDB)? The choice impacts the complexity of change event parsing and the need for specific connectors or drivers.
  • Event ordering guarantees: Should we guarantee strict ordering of events across all tables, or is it acceptable to process events from different tables in parallel? This affects the complexity of the event processing pipeline and consumer design.
  • Event payload format: Should we use raw database change events or transform them into a normalized, domain-specific event format? The former provides more granular information but requires consumers to understand database structures.
  • Event retention policy: How long should we retain processed events in the event store? This impacts storage costs and compliance requirements.
  • Consumption model: Should we support real-time streaming or batch consumption of events? This affects the choice of messaging systems and consumer architecture.

Known trade-offs and justifications

Trade-offOption 1Option 2Justification
Event FormatRaw database eventsNormalized domain eventsRaw events provide more granular information but increase consumer complexity; normalized events simplify consumption but lose some detail
Consistency ModelStrong consistencyEventual consistencyStrong consistency ensures data integrity but may impact performance; eventual consistency allows for better throughput
Processing StrategySynchronous processingAsynchronous processingSynchronous ensures immediate consistency but blocks the database; asynchronous provides better scalability but introduces eventual consistency
Storage StrategySingle event storeSeparate stores per sourceSingle store provides unified access but may become a bottleneck; separate stores offer better scalability and isolation
Event VersioningSchema evolution with backward compatibilityFixed schema with breaking changesBackward compatibility requires more complex event handling but provides better consumer resilience

Risks and mitigation strategies

  • Data Loss Risk: Risk of missing database changes during system downtime or connector failures. Mitigation: Implement a robust retry mechanism with exponential backoff and maintain a durable event store with proper checkpointing.

  • Performance Impact: CDC processing may introduce latency or resource contention on the source database. Mitigation: Use efficient change tracking mechanisms (e.g., PostgreSQL logical replication), implement proper connection pooling, and monitor database performance closely.

  • Event Ordering Issues: Events from different tables or sources may arrive out of order, potentially causing data inconsistency. Mitigation: Implement sequence numbers and timestamp-based ordering in the event store, and design consumers to handle out-of-order events gracefully.

  • Consumer Failure Risk: If downstream consumers fail or become unavailable, events may not be processed. Mitigation: Implement dead letter queue strategies, circuit breaker patterns, and retry mechanisms with exponential backoff.

  • Schema Evolution Risk: Changes to source database schemas may break event consumers. Mitigation: Implement schema versioning, provide backward compatibility, and use schema registry for validation.

Technical debt acknowledged

  • Connector Complexity: Supporting multiple database systems introduces significant technical debt in terms of connector maintenance, testing, and compatibility issues.

  • Event Store Design Limitations: The initial event store design may not scale well for high-volume, low-latency requirements without significant refactoring.

  • Error Recovery Complexity: The current error handling and recovery mechanisms may not adequately handle complex failure scenarios, requiring future refactoring.

  • Monitoring Gaps: The current observability design may not provide sufficient visibility into the CDC pipeline's performance and health at scale.

  • Event Payload Bloat: Raw database event payloads may contain excessive metadata that increases storage and processing overhead, requiring future optimization.

  • Consumer Isolation: The current design assumes all consumers can handle all events, which may not scale well for specialized consumer requirements.

Was this article helpful?

Topics in this article

More from Backend LLD

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.