Video in progress
When you use the Command pattern for background jobs, the commands are stored in the database. What problems do you run into and how do you solve them?
A command is no longer in memory: it's stored as JSON and executed at another time, perhaps by a different version of the code. The main problems: the serialization format changing, repeated side effects on re-execution (idempotency), retries on failure, and two workers picking up the same job.
📖 Answer
With an in-memory Runnable everything is easy. But if jobs have to survive a restart, a command is a row in a table:
create table job (
id bigserial primary key,
type varchar(64) not null,
payload jsonb not null,
status varchar(16) not null,
attempts int not null default 0,
run_after timestamptz not null
);
New problems come up here.
Versioning. A SendInvoice payload saved before the deploy has an email field, while the new code expects recipientId. Deserialization fails. Treat the command class as an "API": don't delete a field, add new ones as optional; for a big change, introduce a SendInvoiceV2 type and keep the old one until the queue is empty. Don't store the Java class name (@class) in the payload: everything breaks during refactoring, and it's a security hole as well.
Idempotency. The worker sent the email but died before setting the status to DONE. The job runs again and the customer gets two emails. There's no complete solution, only mitigation: give the external system an idempotency key, and add an "was this already done?" check.
Two workers taking one job. Claim the row with select ... for update skip locked, or with update ... set status='RUNNING' where id=? and status='NEW': if 1 row changed, you got it.
A poison job. A command that always fails spins forever. You need an attempts limit, an exponential run_after, and a FAILED state.
Before writing all of this by hand, look at ready-made solutions: JobRunr, db-scheduler, Quartz or a message broker.
Sign up to mark studied questions and save your progress.