Much of CASHPOCKET moves by date, not by request. A campaign opens when its start date arrives, recruitment closes at a deadline, rewards are paid after a review period, reminders go out three days before a deadline. All of that is scheduled work, and the server that does it runs as two identical processes.

The problem

pm2 runs the server in cluster mode with two instances. Both load the same entry file. If that file starts a scheduler, there are two schedulers, and every job fires twice within the same second.

For most of what the jobs do, twice is not a harmless inefficiency.

  • A job that pays rewards would start two payouts for each tester.
  • A job that sends a KakaoTalk reminder would send it twice. Alert messages are billed per message and read by real customers.
  • A job that settles a campaign’s unused budget would start two refunds to the advertiser.

The reward has a second defence in the data layer: a paid-at claim and an idempotency key stop a repeated payout from moving points. A message has none. Once it is handed to the provider it is sent. The cleanest fix is for the second scheduler not to exist.

One scheduler

A sequence with four participants: instance 0 and instance 1, both pm2 cluster workers, an /api job route that checks the job key, and MongoDB holding campaigns and points. When both instances start, instance 0 finds that its instance id is 0 and starts node-cron, while instance 1 finds that its id is not 0 and skips the scheduler. At 00:01 Korea time, instance 0 posts the job to the route with a job key, and the route moves the campaigns whose start date came in MongoDB. The legend separates the one scheduler, the skipped start, and the write that is made once.
Figure 1. Two instances boot the same code, and only instance 0 starts the scheduler. Jobs call the server's own API with a job key, and either instance may serve that call.

pm2 gives every process in a cluster a numeric instance id through the environment. The entry file starts listening for HTTP first, then loads the scheduler module and asks it to initialise. The first thing the initialiser does is read that id. If it is defined and is not zero, it returns without registering anything.

Two further switches follow, in order.

initScheduler(env):
    id = env.instanceId                    # set by pm2 for each process in the cluster
    if id is defined and id != "0":
        return                             # not the scheduler instance

    if env.CRON_ENABLED == "false":
        return                             # global off switch
    if env.APP_ENV == "staging" and env.CRON_ENABLED != "true":
        return                             # staging is off unless switched on

    register every job in the Etc/UTC timezone

A staging server boots the same code against its own database. With the scheduler on by default it would run the daily jobs against staging data and, depending on the provider policy, send messages. It therefore needs an explicit switch to run them at all. A second, global switch turns scheduling off everywhere.

Jobs call the API

Most jobs contain one statement: a POST to a route on the server itself, with a job key in a header. The route checks the key and does the work.

That choice has three consequences.

  • One implementation. The route that a schedule triggers at midnight is the same one an operator can trigger by hand, with the same checks.
  • One authentication rule. A job route checks a key sent in a request header, and tests cover that check.
  • Either instance can do the work. The scheduler lives in instance 0, but its HTTP call is balanced across the cluster like any other request. The one-instance rule is about who starts a job, not who executes it.

A few jobs run in the scheduler process itself because they are operations work with no API surface: the nightly database backup to object storage, the removal of files that were soft-deleted more than 30 days ago, and the cleanup of old inquiry attachments.

What runs when

Times are Korea time. The scheduler itself is registered in UTC.

WhenJobWhat it moves
00:01Campaign startApproved campaigns whose recruitment start has arrived become active
00:02Recruitment closeCampaigns past their deadline close recruitment
00:03Submission deadlinesApplications whose selection was never confirmed are rejected. Active testers past their personal deadline are closed without a reward
07:50Reward payoutCompleted applications without a paid-at timestamp are paid
08:00Campaign closureSeven days after the review deadline the campaign closes, and anyone still unpaid is paid
10:00Deadline reminderA reminder three days before the review deadline
12:00Automatic selectionTwo days after the deadline, pending selections are confirmed, the rest rejected, and unused budget goes back to the advertiser through the ledger
03:05BackupA database dump to object storage
03:10File cleanupFiles soft-deleted more than 30 days ago are removed from storage and the database
03:35, 03:40Deal settlementCashback is paid first, then deal budgets are settled
03:45Video budget refundUnused budget of advertiser videos whose exposure period has ended is returned
09:20Ad metricsSpend and results per ad are synced from the ad platform
Every 5 minutesScheduled pushPush campaigns whose time has come are sent, and ones stuck mid-send are reclaimed
Thursday 17:30Withdrawal digestA weekly summary of pending withdrawals for the people who process them

Two things about this table matter.

The campaign jobs run a minute apart in lifecycle order: start, close, deadlines. A campaign that should both start and close on the same night passes through the states in sequence.

The two deal jobs run five minutes apart in a fixed order. Cashback to testers goes first and the budget settlement second, so unused budget is never computed from a budget that still owes a payout. The video budget refund follows five minutes later, which keeps the three jobs’ ledger writes from overlapping.

Jobs that can run twice anyway

The one-instance rule removes the systematic duplicate. It does not remove every duplicate: an operator can trigger a route by hand while the schedule is running, and two different jobs can cover the same application. The job bodies are written for that.

  • The reward payout claims each application by setting its paid-at timestamp conditionally, then pays with a key built from the campaign and the tester. The 07:50 and 08:00 jobs overlap, and the second finds nothing left to pay for an application the first has claimed.
  • The push dispatcher marks a campaign as sending before it sends, so a second run does not pick it up, and reclaims one that has been in that state too long.
  • The date-driven status jobs are conditional updates on the current status. Running one twice moves nothing the second time.

Failure modes

What happensWhat the system doesCovered by
Both instances bootInstance 1 reads a non-zero id and registers nothingThe check at the top of the initialiser
A staging server bootsNo jobs unless the switch is set to trueA test with four cases on the environment gate
A staging server is pointed at production stateThe server refuses to bootA test on the staging guard
A job route is called without the keyThe request is rejectedTests on the key check
A reward job runs twiceThe paid-at claim and the reward key stop the second payoutTests on the reward service against the kernel
A scheduled push is interrupted mid-sendThe next run reclaims itThe dispatcher’s reclaim rule

Limits

  • The rule is positional. It relies on pm2’s instance ids on one machine. Two machines would each have an instance 0, and the design would then need a lock in the database or Redis instead of an id check.
  • The instance check itself has no unit test. The environment gate has four cases. The id check does not have one yet.
  • A job that fails is not retried by the scheduler. It runs again at its next scheduled time. The daily jobs select everything that is due, not only what became due that day, so a missed night is picked up by the next one.