Skip to main content

Backfill Pipeline

GitGazer only sees workflow and pull-request activity that happens after a webhook is configured. The backfill pipeline fills the gap by importing historical data straight from the GitHub REST API — entirely inside AWS, with no long-running process tied to an operator's laptop.

It reuses the same ingestion path as live webhooks: every backfilled record flows through insertEvent(), so the database upserts, freshness guards, and tenant isolation behave identically to real-time events.

Looking for how to run it?

This page explains how the pipeline works internally. To trigger an import, see the Backfilling Historical Data user guide.

Why serverless​

The original backfill was a CLI (packages/import) that ran on a developer's machine. A dropped VPN, a closed laptop, or a sleeping host would interrupt a multi-hour import. The serverless design eliminates that fragility:

  • Work is split into thousands of tiny tasks, each processing at most one API page or one entity.
  • Every task retries independently through SQS, so a transient failure never restarts the whole run.
  • A run resumes automatically — there is nothing to keep online.

High-Level Flow​

One Lambda, Two Entry Modes​

A single backfill-worker Lambda handles both how a run starts and how it progresses. The handler inspects the incoming event: an SQS event carries a Records array, anything else is a direct invoke.

  • Direct invoke — The JSON payload is validated as the initial discover task and pushed onto the queue. This is how an operator kicks off a run. The function returns immediately.
  • SQS invoke — Each record is a task, processed with function_response_types = ["ReportBatchItemFailures"] (the same partial-batch-failure contract as the webhook worker). Follow-up tasks are self-enqueued for fan-out. Failed tasks are retried by SQS, then parked in the DLQ.

This keeps the footprint to one Lambda + one queue + one DLQ, which suits a manually triggered, one-off workflow.

Task Contract​

Tasks are JSON bodies on the queue, modeled as a discriminated union (mirroring the existing WebhookMessage | OrgMemberSyncTask routing). The kind field selects the handler, and each handler returns zero or more follow-up tasks that the worker enqueues.

Task kindWork performedFan-out it emits
discoverList repos for owner (or a single repo, or a topic filter)one repo task per repository
repoSeed pagination for one repositoryruns_page{page:1} and/or prs_page{page:1}
runs_page{page}Fetch one page of workflow runsa workflow_run task per run + runs_page{page+1} if the page is full
prs_page{page}Fetch one page of pull requestsa pull_request task per in-range PR + prs_page{page+1} if more remain
workflow_runIngest the threaded run; fetch its jobs too(none — writes to the database)
pull_requestFetch the PR detail + reviews, transform, ingest(none — writes to the database)

Every task carries the run context: integrationId, owner, eventTypes, and optional since / until date bounds.

Why chained pagination​

Because each task handles at most one page or one entity, no single invocation can run long enough to hit the 60-second Lambda timeout. The work naturally spreads across many short invocations, each independently retryable. This is what makes a run resilient and resumable.

Per-entity task payloads​

A workflow_run task carries the full run object ({ repo, run }), threaded straight from the runs_page listing — the list and single-run endpoints return the identical workflow-run shape, so re-fetching each run individually would burn one wasted GitHub call per run. A pull_request task carries { repo, pullNumber }: the list endpoint omits the diff stats (additions, deletions, changed files, commits) that the importer persists, so the per-PR detail fetch is still required. At processing time each handler also needs the entity's repository (and organization) — which it reuses from Postgres when already imported, fetching from GitHub only when missing (see Reusing sub-dependencies already in the database). Run objects stay well under SQS's 256 KB message limit.

Reusing sub-dependencies already in the database​

Importing any entity first requires its repository — and, for org-owned repos, its organization — to exist. GitHub supplies both through a single GET /repos/{owner}/{repo} call (fetchRepo), whose response embeds the organization. To minimize requests against the rate-limited GitHub API, the workflow_run and pull_request handlers check Postgres first: when the repository (resolved by owner login + name, RLS-scoped to the integration) is already stored, its repository and organization rows are rebuilt into the payload the importer reads and the GitHub fetch is skipped entirely.

This pays off on re-runs and incremental backfills, where the repository was imported by an earlier run or a live webhook. When the repository is absent, the handler falls back to fetchRepo. Either way the resolved payload is cached per container, so repeated tasks for the same repository neither re-read the database nor re-call GitHub. The list-page fetches (runs_page, prs_page) and the per-entity detail fetches (fetchWorkflowJobs, fetchPullRequest, fetchPullRequestReviews) are unaffected — only the repository sub-dependency is served from the database.

Because the reused payload is rebuilt from stored rows, a backfill does not refresh repository or organization metadata (visibility, default branch, topics, organization description) for an already-imported repository — the upsert simply rewrites the existing values, so it can never overwrite fresher data, but it also won't pull changes. Live webhooks keep that metadata current; and a repository or owner rename changes the lookup key, which misses the stored row and falls back to a fresh fetchRepo.

Event-type filtering​

The eventTypes array flows through every task. Handlers use it to skip work the operator didn't ask for:

  • repo only seeds runs_page if workflow_run or workflow_job is requested, and only seeds prs_page if pull_request or pull_request_review is requested.
  • workflow_run skips the jobs fetch unless workflow_job is requested.
  • pull_request skips the reviews fetch unless pull_request_review is requested.

Date windowing​

since / until (each YYYY-MM-DD) bound the import:

  • Workflow runs use GitHub's server-side created query filter (since..until, >=since, or <=until).
  • Pull requests are listed newest-first by updated_at and filtered client-side. Because the list is descending, once the oldest PR on a page predates since, pagination stops early — no later page can contain in-range PRs.
  • GitHub exposes at most 1,000 runs per workflow-runs query (GITHUB_RUNS_RESULT_CAP). runs_page stops paginating at that ceiling and logs a warning when total_count exceeds it, so any runs beyond the first 1,000 in a window are skipped — narrowing since / until is the way to reach them.

SQS Queue Architecture​

Standard, not FIFO​

The backfill queue is a standard queue — backfill needs parallelism, not ordering. The upsert freshness guards make duplicate and out-of-order delivery safe, so there's no reason to pay FIFO's throughput cost.

PropertyValue
TypeStandard
Visibility timeout360 s (6× the 60 s Lambda timeout)
Message retention4 days
Max message size256 KB
PollingLong polling (5 second wait)
EncryptionKMS
RedrivemaxReceiveCount: 10 → DLQ

Dead-Letter Queue​

A task that fails ten times is moved to the DLQ, which retains messages for 14 days. The limit is high because a rate-limited task can legitimately be redelivered several times across limit-reset windows before it succeeds. DLQ depth is the canonical "something went wrong" signal for a run — a CloudWatch alarm fires whenever any message lands there (when alarm notifications are enabled).

Concurrency cap​

The event-source mapping sets scaling_config { maximum_concurrency = N } (the backfill_max_concurrency variable, default 2, minimum 2). This bounds how many workers call GitHub in parallel, keeping the fan-out from tripping GitHub's secondary rate limits.

GitHub Authentication​

Backfill authenticates as a personal access token (PAT) per integration, not via the GitHub App — not every integration is guaranteed to have an App installation.

  • Each PAT lives in its own Secrets Manager secret named <prefix>/<integrationId>, where the prefix is gitgazer/backfill/<workspace> (for example gitgazer/backfill/default). Namespacing by Terraform workspace prevents cross-environment collisions.
  • resolvePat(integrationId) reads the secret as a raw string (not JSON), trims it, and caches it for the container lifetime to avoid a Secrets Manager call per task.
  • IAM is scoped to the prefix gitgazer/backfill/<workspace>/* for least privilege.

Network Egress​

The worker runs in the VPC private subnets for RDS access, where GitHub (IPv4-only) is unreachable directly. All GitHub calls therefore go through the shared proxyFetch → HTTP proxy Lambda path — the same route the org-sync worker uses.

Rate-Limit Handling​

proxyFetch performs no retries when the proxy is enabled, so the backfill GitHub client (fetchJson) implements its own bounded retry, and SQS provides the outer safety net.

The wait time is chosen in priority order:

  1. The retry-after header (seconds), if present — GitHub sends this for secondary/abuse limits.
  2. x-ratelimit-remaining: 0 plus x-ratelimit-reset → wait until the reset epoch (plus a 1 s buffer).
  3. Otherwise exponential backoff: min(8 s, 500 ms · 2^(attempt-1)) with up to 30% jitter.

Inline retries happen only when the wait is ≤ 20 seconds and within the 4-attempt budget. A longer wait (a primary-limit reset can be many minutes out) instead throws a GitHubApiError carrying the wait. The worker then extends the SQS message's visibility timeout until the limit resets (capped at SQS's 12-hour maximum) and reports the task as failed, so SQS re-delivers it after the reset — no Lambda compute is burned waiting. Other failures are re-delivered after the queue's 360-second visibility timeout.

Idempotency & Safety​

Re-running a backfill, or retrying any individual task, is safe. Ingestion goes through the same insertEvent() path as live webhooks, whose upserts apply freshness guards (upsertWorkflowRuns / upsertWorkflowJobs return stale=true rather than overwriting newer rows). Duplicate and out-of-order arrivals are therefore harmless — which is exactly what lets the queue be standard and the concurrency be parallel.

Storage growth in the events backup table

Alongside the deduplicated domain tables, insertEvent() appends every record to the append-only events backup table, which has no dedup or freshness guard. A backfill writes one events row per workflow run, job, pull request, and review it processes — and re-running an overlapping range appends those rows again. Large or repeated imports can grow this table substantially. Budget RDS storage accordingly, and prune events on a retention schedule if you don't need it for replay.

IAM & Permissions​

The worker's execution role grants the minimum it needs:

PermissionWhy
sqs:ReceiveMessage / DeleteMessage / GetQueueAttributes / SendMessageConsume tasks and self-enqueue fan-out
sqs:ChangeMessageVisibilityDefer rate-limited tasks until the limit resets
secretsmanager:GetSecretValueRead DB config + per-integration PATs (prefix-scoped)
kms:Decrypt / GenerateDataKey / EncryptDecrypt secrets and queue messages
rds-db:connectIAM-auth database connection
VPC access + CloudWatch LogsRun in-VPC and emit structured logs

Notably absent: any WebSocket or alerting permissions. Backfill writes straight to the database and skips those live side effects by design.

Monitoring​

  • CloudWatch Logs — The worker logs structured JSON (AWS Powertools Logger) to a dedicated log group with 30-day retention.
  • DLQ alarm — Fires when any task exhausts its retries and lands in the dead-letter queue.
  • Queue depth — ApproximateNumberOfMessages + ApproximateNumberOfMessagesNotVisible on the backfill queue both reaching zero indicates a run has finished.
  • Lambda duration alarm — The backfill-worker is registered in the standard monitored-Lambda alarm set.