Quick revision
The short answer
We define a DefaultLockRepository on the application's DataSource, which uses Spring Integration's INT_LOCK table, wrap it in a JdbcLockRegistry, and register a LockRegistryLeaderInitiator with that registry, which keeps trying to acquire and renew a lock named after the role. An @EventListener for OnGrantedEvent starts the index rebuild and one for OnRevokedEvent stops it. If the leader pod crashes, its lock row expires after the repository's time to live, 10 seconds by default (check your version), and another pod takes over; if the leader merely hangs and resumes, another pod may already be leader, so the task must check leadership before each unit of work and use idempotent or fenced writes.
What to remember
In this answer, we built leader election for a six-pod Spring Boot service with a DefaultLockRepository on the application's DataSource and the INT_LOCK table, a JdbcLockRegistry and a LockRegistryLeaderInitiator with a role-named candidate. OnGrantedEvent starts the index rebuild and OnRevokedEvent stops it, and the event's context lets the leader yield. A crashed leader is replaced after the lock's time to live, 10 seconds by default, while a hung leader can briefly overlap with the new one, so the task checks leadership per batch and uses idempotent or fenced writes. Kubernetes leases, ZooKeeper with Curator and Redis follow the same pattern.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We define a DefaultLockRepository on the application's DataSource, which uses Spring Integration's INT_LOCK table, wrap it in a JdbcLockRegistry, and register a LockRegistryLeaderInitiator with that registry, which keeps trying to acquire and renew a lock named after the role. An @EventListener for OnGrantedEvent starts the index rebuild and one for OnRevokedEvent stops it. If the leader pod crashes, its lock row expires after the repository's time to live, 10 seconds by default (check your version), and another pod takes over; if the leader merely hangs and resumes, another pod may already be leader, so the task must check leadership before each unit of work and use idempotent or fenced writes.
Why this question is asked
Many Spring Boot services run several replicas but have one job that must run on only one of them at a time, such as rebuilding a report index, sending a daily digest or polling an external system. Spring Integration provides leader election on top of a lock registry, and backing it with JDBC means the database we already have becomes the coordinator, with no new infrastructure. Interviewers ask this coding question to see whether we can wire it correctly and, more importantly, whether we understand what happens when the leader is slow rather than dead. In this answer, we will recap the pieces, write the configuration, start and stop the task on leadership events, walk through crash and hang scenarios, and compare the alternatives.
1A Quick Recap of the Pieces
Spring Integration models leader election with a few small types. A Candidate has an id (this pod) and a role (the name of the job it wants to lead). A LockRegistry hands out distributed locks by key. LockRegistryLeaderInitiator joins the two: it runs a background loop that tries to obtain the lock named after the role, and while it holds it, keeps renewing it. When it gets the lock it publishes an OnGrantedEvent, and when it loses or gives it up, an OnRevokedEvent.
JdbcLockRegistry implements the registry with a database table. Its DefaultLockRepository stores one row per lock in INT_LOCK with the lock key, the region, the client id of the holder and the time it was created or last refreshed. A lock whose row has not been refreshed within the time to live counts as expired and can be taken by another client. The table comes from Spring Integration's schema scripts, for example schema-postgresql.sql in the spring-integration-jdbc jar; Spring Boot can run it with spring.integration.jdbc.initialize-schema, or we add it to our Flyway or Liquibase migrations.
2Configuring the Leader Initiator
The configuration is three beans. We give each pod a stable, unique candidate id, such as the pod name from the HOSTNAME environment variable, so logs show who leads.
Notice that all six pods run exactly this configuration. Each initiator tries the same lock key, only one succeeds, and the others keep retrying in the background. LockRegistryLeaderInitiator is a SmartLifecycle bean, so it starts with the application context and stops, releasing the lock, during a graceful shutdown, which makes rolling deployments hand over leadership quickly instead of waiting for expiry.
3Starting and Stopping the Task on Leadership Events
The task reacts to the two events. On OnGrantedEvent we start the rebuild on a separate executor, so the event thread is not blocked; on OnRevokedEvent we ask it to stop. The event's context also lets the leader give up leadership deliberately, for example after finishing the day's work, through context.yield().
4When the Leader Pod Crashes or Hangs
If the leader pod crashes, it stops refreshing its INT_LOCK row. After the repository's time to live, 10 seconds by default (check your version), the row counts as expired, the next pod whose initiator tries the lock acquires it, receives OnGrantedEvent and starts the rebuild. So a crash costs roughly the TTL plus one retry interval of downtime for the job.
A hang is more dangerous. Suppose the leader enters a 20-second GC pause. Its lock is not refreshed, it expires after 10 seconds, and pod 5 becomes leader and starts rebuilding. Then pod 3 wakes up in the middle of writing a batch. Its in-memory state still says leader, and until its initiator notices the lost lock and publishes OnRevokedEvent, it keeps writing. For a short time, two pods run the task.
That is why the code checks leadership before every unit of work, which shortens the overlap to at most one batch, and why each write must be safe if it happens twice or out of order. Idempotent writes, such as upserting each document by its id with the same computed content, make duplicate work harmless. Where order matters, a fencing value, such as a leadership epoch stored with the data and checked in the write's WHERE clause, makes the database reject writes from a stale leader.
7 messages in order. Play them, or step through them one at a time.
Checking leadership per batch and idempotent writes keep the overlap harmless.
5Other Options That Follow the Same Pattern
Spring Integration's leader abstraction is not tied to JDBC. Spring Cloud Kubernetes offers leader election based on Kubernetes objects (a ConfigMap or a Lease), which suits services that should not depend on a database for coordination. For ZooKeeper, Spring Integration's LeaderInitiator for Zookeeper and Apache Curator's LeaderLatch provide the same granted and revoked semantics. A RedisLockRegistry also works with LockRegistryLeaderInitiator.
Whichever backend we choose, the same rules apply: unique candidate ids, a TTL that balances failover speed against false takeovers during pauses, work split into small units with a leadership check before each, and idempotent or fenced writes because two leaders can briefly overlap.
| Backend | Uses | Good when |
|---|---|---|
JdbcLockRegistry | INT_LOCK table in the app database | a database is already shared by all pods |
| Spring Cloud Kubernetes | Kubernetes ConfigMap or Lease objects | running on Kubernetes, no extra store |
Zookeeper / Curator LeaderLatch | ephemeral sequential znodes | ZooKeeper is already operated |
RedisLockRegistry | Redis keys with expiry | Redis is already shared |
6Follow-up questions
Why does the leader need to check leadership inside the loop if it already gets OnRevokedEvent?
Because the revoked event can arrive late. After a pause, the pod continues executing before its initiator thread has noticed the lost lock. A check before each batch, plus cancelling the future on revoke, keeps the overlap to one small unit of work.
What TTL should we choose?
Long enough to survive normal GC pauses and database hiccups without false takeovers, short enough that a crashed leader is replaced quickly. The default of about 10 seconds suits a daily index rebuild; a job that must restart within seconds might use less, with careful pause monitoring.
What happens if the database is unavailable?
No pod can acquire or renew the lock, so the current leader loses leadership once its lock expires and nobody takes over until the database returns. For a job that writes to the same database, that is usually the right behaviour, since it could not work anyway.
7Conclusion
In this answer, we built leader election for a six-pod Spring Boot service with a DefaultLockRepository on the application's DataSource and the INT_LOCK table, a JdbcLockRegistry and a LockRegistryLeaderInitiator with a role-named candidate. OnGrantedEvent starts the index rebuild and OnRevokedEvent stops it, and the event's context lets the leader yield. A crashed leader is replaced after the lock's time to live, 10 seconds by default, while a hung leader can briefly overlap with the new one, so the task checks leadership per batch and uses idempotent or fenced writes. Kubernetes leases, ZooKeeper with Curator and Redis follow the same pattern.
Open with
I'd use three beans. A DefaultLockRepository on the application's DataSource, which uses the INT_LOCK table from Spring Integration's schema scripts, so I'd add that to our migrations or let Spring Boot initialise it.
Then, if they want more
A JdbcLockRegistry on top of that repository. And a LockRegistryLeaderInitiator with that registry and a DefaultCandidate whose id is the pod name and whose role is, say, report-index. All six pods run the same config; the initiator keeps trying to acquire and renew the lock named after the role, and only one holds it.
My job class has an @EventListener for OnGrantedEvent that starts the rebuild on its own executor, and one for OnRevokedEvent that cancels it; the event's context also lets the leader yield deliberately.
If the leader pod crashes, its lock row stops being refreshed and expires after the repository's time to live, ten seconds by default, though I'd check the version, and another pod acquires it and gets OnGrantedEvent.
The tricky case is a hang, like a long GC pause: the lock expires, another pod becomes leader, and the old one wakes up still thinking it leads. So the task checks leadership before each batch and writes idempotently, or with a fencing value, because two leaders can briefly overlap.
The same pattern works with Spring Cloud Kubernetes leader election or Curator's LeaderLatch with ZooKeeper.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Show how to elect a leader with Spring Integration's LockRegistryLeaderInitiator backed...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/4189cc3989/