Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service runs a nightly billing job with ScheduledExecutorService. After scaling to three instances, customers are billed three times. Compare options to fix this.

Each of the three instances runs its own ScheduledExecutorService, so the nightly job runs once per instance and every customer is billed three times. We can let only one instance run each execution with a database-backed lock such as ShedLock, use Quartz in clustered mode so schedules and locks live in a shared database, or move the job out of the service into an external scheduler such as a Kubernetes CronJob. Whichever we choose, billing itself must be idempotent, with a unique key per customer and billing period.

Why this question is asked

A scheduler inside the application is convenient when there is one instance, and it quietly becomes wrong the day we scale out. For most periodic tasks, running three times only wastes work, but for billing it charges customers three times. Interviewers ask this scenario because it tests whether we understand that in-process schedulers know nothing about each other, and whether we design for the scheduler's own failures too. In this answer, we will see why the job runs three times, compare three ways to run it once, ShedLock, clustered Quartz and an external scheduler, and then make billing safe even when the scheduler gets it wrong.

1Why Every Instance Runs the Job

A ScheduledExecutorService lives inside one JVM. When the service starts, its code schedules the billing job for 02:00, and that schedule exists only in that JVM's memory. With three instances, three JVMs start, each schedules its own billing job, and at 02:00 each one runs it. No instance knows the others exist.

Java
@PostConstruct
void scheduleBilling() {
long delay = Duration.between(now(), next2am()).toMillis();
scheduler.scheduleAtFixedRate(billing::runNightly, delay, TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
}
// instance-1 02:00:00 billing started: 41,200 customers
// instance-2 02:00:00 billing started: 41,200 customers
// instance-3 02:00:01 billing started: 41,200 customers -> every customer billed 3 times

So the problem is not a bug in the scheduler. It is that scheduling became a cluster-wide decision while the scheduler is still per instance. We need something shared that decides which instance runs each execution, or we move the decision out of the instances entirely.

2Option 1: A Database Lock With ShedLock

ShedLock is a small library that makes a scheduled task take a named lock in a shared store, usually the service's own database, before it runs. Every instance still triggers the job at 02:00, but only the one that acquires the lock runs it; the others see the lock is taken and skip that execution.

Java
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30M")
class SchedulingConfig {
@Bean LockProvider lockProvider(DataSource ds) {
return new JdbcTemplateLockProvider(ds); // uses a shedlock table
}
}
@Scheduled(cron = "0 0 2 * * *", zone = "UTC")
@SchedulerLock(name = "nightlyBilling", lockAtMostFor = "PT3H", lockAtLeastFor = "PT5M")
public void runNightly() { billing.runNightly(); }
// instance-1 02:00:00 lock acquired, billing started
// instance-2 02:00:00 lock held elsewhere, skipped
// instance-3 02:00:01 lock held elsewhere, skipped

Two settings matter. lockAtMostFor is a safety net: if the instance running the job dies, the lock expires after this time so a later execution can run; it must be longer than the job's longest run, or a second instance might start while the first is still billing. lockAtLeastFor keeps the lock for a minimum time, so an instance whose clock is a few seconds behind does not start the same execution again after a fast run finishes. Here we moved to Spring's @Scheduled; with a plain ScheduledExecutorService, ShedLock's LockingTaskExecutor can wrap the task the same way.

ShedLock is the smallest change, but it only prevents concurrent runs. It does not remember whether last night's run happened, so if the running instance dies halfway, nobody retries until the next night.

3Option 2: Quartz in Clustered Mode

Quartz is a full scheduler library. In clustered mode, it stores jobs, triggers and their state in database tables through its JDBC job store, and all instances share those tables. When a trigger fires, the instances coordinate through database locks so exactly one of them runs the job. Quartz also tracks misfires, runs that were missed because no instance was up, and can recover jobs that were running on an instance that crashed, if the job is marked to request recovery.

Properties
spring.quartz.job-store-type=jdbc
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=20000
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO

This is more machinery: extra tables, a scheduler to understand and configure, and clock synchronisation between instances matters. In return, we get a real job scheduler with history, misfire handling and recovery inside the service. It fits well when a service has many scheduled jobs with complex calendars.

4Option 3: An External Scheduler

The third option takes scheduling out of the long-running service. A Kubernetes CronJob, or a cloud scheduler or workflow tool, starts a separate run at 02:00: either a short-lived pod that runs the billing code and exits, or a call to an internal endpoint that starts the job. Because only one thing triggers the run, the instance count of the service does not matter.

YAML
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-billing
spec:
schedule: "0 2 * * *"
timeZone: "UTC"
concurrencyPolicy: Forbid # never start a run while the last one is still going
startingDeadlineSeconds: 3600 # still start if the controller was late by up to 1 h
jobTemplate:
spec:
backoffLimit: 2 # retries: billing must be idempotent
template:
spec:
restartPolicy: Never
containers:
- name: billing
image: registry.example.com/billing-job:1.42
Comparing the options
OptionRuns once becauseStrengthsCosts
ShedLocka lock row in the shared DBtiny change, keeps code in placeno missed-run recovery
Quartz clusteredDB-coordinated triggersmisfires, recovery, historymore tables and configuration
Kubernetes CronJobone external triggerisolated resources, platform retriesrare double or missed runs
Idempotent billingduplicates have no effectsafe under every optionneeds a unique key design

This separates batch work from request-serving pods, gives us job history and retries from the platform, and lets the job have its own resources. But there is a catch: Kubernetes documents that a CronJob may occasionally create two jobs for one schedule, or none, so even here we cannot rely on exactly once.

5Making Billing Idempotent Whatever Schedules It

Every scheduler can fail in a way that runs the job twice: a lock that expires during a long run, a retry after a crash halfway through, a CronJob that fires twice. So the real protection is in the billing logic. Billing a customer for a period is made idempotent, meaning that doing it twice has the same effect as doing it once. The simplest way is a unique key for each customer and billing period, enforced by the database.

SQL
CREATE TABLE invoice (
customer_id BIGINT NOT NULL,
period CHAR(7) NOT NULL, -- '2026-11'
amount_cents BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (customer_id, period)
);
INSERT INTO invoice (customer_id, period, amount_cents)
VALUES (42, '2026-11', 1999)
ON CONFLICT (customer_id, period) DO NOTHING; -- first run: 1 row; any repeat: 0 rows

The job charges the customer only when the insert actually created the row, and it passes the invoice key as an idempotency key to the payment provider, so a retry after a crash cannot charge twice either. With this in place, a second run of the job is harmless: it finds every invoice already present and does nothing. My choice would be an external scheduler or ShedLock for running once in the normal case, depending on whether the team already runs CronJobs, and idempotent billing in every case.

6Follow-up questions

Why not just run the scheduler on one designated instance?

Because instances are replaceable: if the designated pod is rescheduled or crashes at 01:59, nothing runs, and during a rolling deploy two pods might both believe they are designated. Leader election solves this properly, but at that point a lock or an external scheduler is simpler.

What happens with ShedLock if the job runs longer than lockAtMostFor?

The lock expires while the job is still running, and another instance could start the same execution. That is why lockAtMostFor must be comfortably longer than the slowest run, and why billing must stay idempotent even with a lock.

How would you clean up the customers already billed three times?

Find duplicate charges for the period from the payment records, refund the extra ones with the provider, tell the affected customers, and only then deploy the fix with the unique key so the problem cannot repeat.

7Conclusion

In this answer, we saw that in-process schedulers run once per instance, so three instances bill three times. ShedLock adds a database lock so only one instance runs each execution, Quartz in clustered mode keeps schedules and locks in shared tables with misfire handling and recovery, and an external scheduler such as a Kubernetes CronJob triggers the job from outside, though it can still occasionally run twice. In every case, billing is made idempotent with a unique key per customer and period and idempotency keys for the payment provider.

What to say in the interviewAbout 90 seconds aloud

Open with

The cause is simple: a ScheduledExecutorService lives inside one JVM, so with three instances there are three independent schedules, and at 02:00 each instance runs billing. There are three ways to make it run once.

Then, if they want more

The smallest change is ShedLock: each instance still triggers the job, but the job first takes a named lock in a table in our database, and only the instance that gets it runs; the others skip.

I would set lockAtMostFor well above the longest run, so a crashed instance cannot hold the lock forever but a slow run is not overtaken. Its weakness is that it does not retry a run that died.

Second, Quartz in clustered mode with the JDBC job store: triggers and state live in shared tables, instances coordinate through database locks, and we get misfire handling and recovery, at the cost of more configuration. Third, take scheduling out of the service: a Kubernetes CronJob with concurrencyPolicy Forbid starts a separate billing run, which isolates batch work from request pods.

But Kubernetes itself says a CronJob can occasionally run twice or not at all. So whatever we pick, the real fix is idempotent billing: an invoice table with a primary key of customer and period, insert with ON CONFLICT DO NOTHING, charge only if the row was created, and pass that key as the idempotency key to the payment provider. Then a duplicate run does nothing.

About this answer

Last updated
12 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 documentation below. 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 "A service runs a nightly billing job with ScheduledExecutorService. After scaling to...": https://scrivio-interview-library.netlify.app/java/executors/e378744f39/