Managing Service Coordination

1. Leader Election Pattern

AspectDetail
PurposeOne instance performs role (singleton task) across cluster
MechanismDistributed lock with TTL or consensus protocol
ToolsZooKeeper, etcd lease, Consul session, K8s lease
Use CasesCron job, partition owner, primary writer

Example: K8s Lease Election

lock := &resourcelock.LeaseLock{
    LeaseMeta: metav1.ObjectMeta{Name: "scheduler", Namespace: "default"},
    Client: client.CoordinationV1(),
    LockConfig: resourcelock.ResourceLockConfig{Identity: hostname},
}
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
    Lock: lock, LeaseDuration: 15*time.Second,
    RenewDeadline: 10*time.Second, RetryPeriod: 2*time.Second,
    Callbacks: leaderelection.LeaderCallbacks{
        OnStartedLeading: func(ctx context.Context) { runScheduler(ctx) },
        OnStoppedLeading: func() { stopScheduler() },
    },
})

2. Distributed Lock Pattern

PropertyRequired
Mutual ExclusionOnly one holder
Deadlock-FreeTTL ensures release on holder death
Fault-TolerantLock service must be HA
Fencing TokenResists stale-holder writes

3. Distributed Consensus Pattern

AlgorithmDescription
PaxosClassic; complex; hard to implement correctly
RaftEquivalent to Paxos; designed for understandability
ZabZooKeeper Atomic Broadcast
PBFTByzantine fault tolerant
QuorumMajority must agree (e.g., 3 of 5)

4. Coordination Service Pattern

CapabilityProvided By
Distributed Locksetcd, ZooKeeper, Consul
Leader Electionetcd lease, K8s lease
Service DiscoveryConsul, etcd, ZooKeeper
Config Distributionetcd watch, Consul KV
MembershipHashicorp Serf, ZooKeeper ephemeral nodes

5. Work Distribution Pattern

StrategyDetail
Queue-BasedWorkers compete on shared queue
Hash-Based ShardingHash(key) → owner instance
Consistent HashingMinimize re-sharding on instance change
Coordinator-AssignedLeader assigns work to followers

6. Task Queue Pattern

ElementDetail
ProducerEnqueues task with payload + priority
WorkerPolls queue, executes, acks
Visibility TimeoutTask hidden during processing; reappears if not acked
DLQFailed-too-many-times tasks parked
ToolsSQS, RabbitMQ, Celery, Sidekiq, Temporal Activities

7. Claim Check Pattern

AspectDetail
ProblemLarge payloads exceed broker message size limits
SolutionStore payload in blob store; pass reference (URL/key) in message
ConsumerFetches payload using claim check ID
CleanupTTL on blob; or consumer deletes after process

Example: Claim Check with S3

String key = "uploads/" + UUID.randomUUID();
s3.putObject(bucket, key, largePayload);
kafka.send("uploads", new ClaimCheck(key, bucket, payload.length()));
// Consumer:
ClaimCheck cc = record.value();
byte[] data = s3.getObject(cc.bucket(), cc.key());

8. Distributed Barrier Pattern

AspectDetail
PurposeN participants wait until all reach barrier, then proceed
ImplementationZooKeeper ephemeral nodes; etcd counter; Redis
Use CaseCoordinated rollout, batch phase boundary

9. Distributed Latch Pattern

AspectDetail
PurposeWait until counter reaches 0 (one-shot)
Use CaseWait for N events before proceeding
ImplementationAtomic counter in Redis/etcd; watcher on 0

10. Scheduling Coordinator Pattern

AspectDetail
RoleDecides where/when work runs across cluster
ConsidersResource availability, locality, priority, fairness
ExamplesK8s scheduler, YARN, Mesos, Nomad
HALeader-elected; followers ready to take over