fix(workers): atomically claim BackgroundJob batches with FOR UPDATE SKIP LOCKED in DbJobPoller

オープン
#61 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
55/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
postgresql, typescript

調査の方向性

Start with apps/workers/src/services/db-job-poller.ts, then read its tests in apps/workers/src/services/db-job-poller.spec.ts and the BackgroundJob model in packages/prisma/schema.prisma. Check how the two queue lanes filter jobs and how retries and soft rescheduling update attempts. Done when replicas claim disjoint batches atomically and the existing status, locking, lane, retry, and rescheduling behavior is covered by updated tests.

索引モデルが issue の本文から書いたものです。

説明

spec workers
Problem Description

In apps/workers/src/services/db-job-poller.ts, pollRealtimeQueue (lines 129-140) and pollMediaQueue (lines 158-169) fetch the top PENDING rows with prisma.backgroundJob.findMany({ take: batchSize }), and then claimAndExecute (lines 183-197) claims each row individually via prisma.backgroundJob.updateMany({ where: { id: candidate.id, status: 'PENDING' } }).

When running multiple worker replicas at 1k-10k+ user scale, every replica fetches the exact same top 20 PENDING rows and races on updateMany, wasting DB queries and delaying jobs #21+ until the first batch is claimed.


Expected Behavior
  1. Each worker replica atomically claims its own disjoint batch of PENDING jobs in a single PostgreSQL query (FOR UPDATE SKIP LOCKED), so replicas never contend on the same rows.
  2. All existing BackgroundJob columns (status = 'PROCESSING', lockedAt, lockedBy, startedAt, attempts), retry/backoff counts, and REALTIME vs MEDIA lane filtering continue to work identically locally (1 worker) and in production (multiple replicas).

Where to Look
  • apps/workers/src/services/db-job-poller.ts (pollRealtimeQueue, pollMediaQueue, claimAndExecute, lines 129-314)
  • apps/workers/src/services/db-job-poller.spec.ts
  • packages/prisma/schema.prisma (BackgroundJob, lines 348-370)

Solution / Implementation Guide
  1. Replace findMany + per-row updateMany with an atomic PostgreSQL claim query using prisma.$queryRaw + Prisma.join(REALTIME_JOB_TYPES) (note: BackgroundJob has no updatedAt column):
    UPDATE "BackgroundJob"
    SET
      "status" = 'PROCESSING',
      "lockedAt" = $now,
      "lockedBy" = $workerId,
      "startedAt" = $now,
      "attempts" = "attempts" + 1
    WHERE "id" IN (
      SELECT "id"
      FROM "BackgroundJob"
      WHERE "status" = 'PENDING'
        AND "runAfter" <= $now
        AND "jobType" IN (...) -- or NOT IN (...) for MEDIA lane
      ORDER BY "priority" ASC, "createdAt" ASC
      LIMIT $batchSize
      FOR UPDATE SKIP LOCKED
    )
    RETURNING *;
    
  2. Update attempts math for post-increment RETURNING * rows in db-job-poller.ts:
    • Soft reschedule (line 286): revert attempts: Math.max(0, job.attempts - 1) instead of candidate.attempts (since RETURNING * already incremented attempts).
    • Hard failure retry/backoff (lines 299-300): change candidate.attempts + 1 >= candidate.maxAttempts to job.attempts >= job.maxAttempts and Math.pow(2, candidate.attempts + 1) to Math.pow(2, job.attempts) so jobs do not lose a retry.
  3. Update unit tests (db-job-poller.spec.ts):
    • Update mocks from prisma.backgroundJob.findMany to prisma.$queryRaw and verify retry exhaustion and soft-reschedule attempts preservation.
主要言語
TypeScript
スター
2
フォーク
1
平均マージ
6分
マージ済み PR(30日)
27

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

sumamakhan761/tryinstance のほかの issue

sumamakhan761/tryinstance の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。