Video in progress
A service runs a heavy multi-hour batch job every night (calculations, an export), and online traffic slows down meanwhile. How do you separate them?
Batch and online load compete for the same resources: pod CPU, the connection pool, the DB and Kafka. I move the batch into a separate deployment or Kubernetes Job with its own pool and limits, and in the DB I route it to a replica or into small, rate-limited chunks.
📖 Answer
A typical case: billing-service serves the API during the day, and at 02:00 a @Scheduled job calculates 3 million accounts. The job runs on those same pods: the CPU is busy, the job takes 8 of HikariCP's 10 connections, and big UPDATEs hold locks on the table. People assumed "there's little traffic at night", but customers in other time zones and payment webhooks arrive at exactly this time.
The layers of separation:
-
The process. Take the batch out of the online pods: the codebase is the same, but a separate deployment or a Kubernetes
CronJob(with a profile that enables only the batch part). Its CPU and memory limits are separate, and the online pods' autoscaling doesn't depend on it. -
DB connections. A separate, small pool for the batch. Even if it asks for many connections, connections stay available for the online load.
-
DB load, the hardest part, since there is one DB:
- if the read is heavy, from a read replica;
- writes in transactions of 1000 rows with a short pause between them, so locks are held briefly;
- adaptive throttling: if DB latency or replication lag goes up, the batch slows itself down;
- for heavy aggregations, an analytical store rather than OLTP.
-
Kafka. If the batch emits millions of events, lag builds up in the consumers and the online events (payment confirmations) get stuck in the queue behind the batch events. A separate topic keeps the online events on their own path.
-
Downstreams. If the batch calls another service, use a rate limit or a bulk API so it doesn't flood that service's online load.
The batch itself must be reliable too: a checkpoint per chunk (with Spring Batch's JobRepository), resuming from where it stopped instead of from the start, and idempotent writes. If a 3-hour job fails at 2 hours 50 minutes and starts over, it won't finish by morning.
The batch has an SLO as well: "finish by 08:00". When the online and batch SLOs are looked at together, the resource decision becomes clear: maybe a separate replica for the batch is the cheapest solution.
Sign up to mark studied questions and save your progress.