Nov 16, 202616 min read

Chargeback Evidence Backend: Deadlines, Packages and Representment

Design dispute intake, evidence files in private storage, a hard submission deadline, a package that is sent once, and outcome tracking, then implement the flow in Go.

Illustration for Chargeback Evidence Backend: Deadlines, Packages and Representment

A cardholder dispute reverses the payment and starts a short clock, usually 7 to 21 days depending on the card network, as Stripe documents in its responding guide. Missing the deadline loses the case automatically, and submitting twice or after the window does not help: the response is final once it is in.

This guide designs a chargeback evidence backend: ingest each dispute once, collect files into a package, submit before the deadline, and record the outcome. It starts with the state machine and the storage rules, then shows the design by hand on AWS and in Go with Encore.

The Chargeback Backend at a Glance

JobPatternHand-built on AWSWith Encore in your AWS account
IntakeOne dispute row per provider ID, opened from a signed webhookAPI endpoint and a processed-events tableRaw endpoint and the same table
Evidence filesPrivate, versioned objects with signed upload URLsS3 bucket and presigned URLsEncore bucket with signed URLs
PackageRequired kinds present before submit is allowedSame databaseSame database
Submit onceConditional UPDATE before due_by, then one provider callSecrets Manager plus the payments APIEncore secret plus the same call
DeadlineWarn, then mark expired if nothing was submittedEventBridge Scheduler or an ECS scheduled taskCron job, Encore platform Managed
Outcomewon, lost or accepted, recorded from a later webhookSame endpoint as intakeSame endpoint as intake
NoticesOpened, due soon, submitted, expired or closed, each sent onceSNS topic and SQS queuePub/Sub topic and subscription

The funds movement stays with the payment provider; this service tracks the case, the evidence and the deadline.

The Dispute State Machine

Treat every dispute as a record that moves through a small set of statuses, with the allowed transitions enforced in SQL. A spreadsheet of due dates, or a status field that any handler can overwrite, is how a package is submitted twice, or how a late upload is treated as a response after the window has closed.

A practical set of statuses is:

StatusMeaningTypical next steps
needs_responseThe dispute has been opened and the deadline is running. Evidence may still be added.submitted, accepted, expired
submittedOne evidence package has been sent to the provider.under_review, won, lost
under_reviewThe issuer has the package and has not decided yet.won, lost
wonThe issuer decided in your favor.Terminal
lostThe issuer upheld the dispute, or the deadline passed without a response.Terminal
acceptedYou chose not to challenge the dispute.Terminal
expireddue_by passed with no submission and no acceptance.Terminal

A few rules are easy to get wrong:

  • The provider's dispute ID is the primary key, and a second charge.dispute.created event for the same ID must not open a second case. Some payments can have more than one dispute, so do not unique on charge_id alone.
  • due_by comes from the provider and is stored when the case is opened. Do not recompute it later from a generic 7-day or 21-day rule, because networks differ, as Stripe's responding guide notes.
  • Submission is a one-way door: after submitted, new files can be stored for your own records, but they are not sent. Stripe documents that you cannot amend a response once it is in.
  • Accepting a dispute is also terminal and needs the same kind of conditional UPDATE as submit, so a click and a webhook cannot accept and submit the same case.
  • expired is written by the deadline job when due_by has passed and the status is still needs_response. A late webhook that tries to submit after that must fail, even if the provider would still accept a file.

Keep the current status, due_by, and a short movement history, which is what you read when a payments lead, a support inbox and the provider dashboard disagree.

A Data Model That Enforces the Rules

CREATE TABLE disputes ( id TEXT PRIMARY KEY, charge_id TEXT NOT NULL, amount_cents INT NOT NULL CHECK (amount_cents > 0), currency TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ( 'needs_response', 'submitting', 'submitted', 'under_review', 'won', 'lost', 'accepted', 'expired' )), due_by TIMESTAMPTZ NOT NULL, submitted_at TIMESTAMPTZ, accepted_at TIMESTAMPTZ, evidence_ready BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE evidence_files ( dispute_id TEXT NOT NULL REFERENCES disputes (id), kind TEXT NOT NULL, object_key TEXT NOT NULL, PRIMARY KEY (dispute_id, kind) ); CREATE TABLE processed_events ( event_id TEXT PRIMARY KEY, received_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE sent_notices ( dispute_id TEXT NOT NULL, kind TEXT NOT NULL, PRIMARY KEY (dispute_id, kind) );

evidence_files keeps one object per kind, such as receipt, customer_communication, shipping_documentation or refund_policy. Replacing a file before submit overwrites the same key in a versioned bucket, so the latest object is what the package includes and earlier versions remain available if a review needs them.

evidence_ready is set when every kind your policy requires for that reason is present. The submit handler should check the flag in the same UPDATE that flips the status, not in a separate read, so a file deletion cannot sneak in between the check and the send.

-- Claim the case for submission. No row means it is too late, -- already submitted, or still missing required evidence. UPDATE disputes SET status = 'submitting' WHERE id = $1 AND status IN ('needs_response', 'submitting') AND evidence_ready AND (due_by > now() OR status = 'submitting') RETURNING id, charge_id;

The provider call that follows should send an idempotency key built from the dispute ID, so a worker that crashes after the UPDATE and retries the HTTP call does not create a second package on the provider side. If the HTTP call fails, keep the row in submitting and retry the same call; rolling the status back to needs_response is how a second reviewer submits a different package.

Outcomes arrive later as charge.dispute.updated or charge.dispute.closed, which Stripe describes in the same responding guide. Map won, lost and under_review onto rows that are already submitting, submitted or under_review. An outcome for a case that is still needs_response is a signal to look at the provider dashboard, not a reason to invent a submission.

Evidence Files and the Deadline

Case owners upload through short-lived signed PUT URLs to a private bucket. The API never streams the files, the objects are not publicly readable, and a signed GET URL for review expires in minutes. The same pattern used for identity documents applies here: check that the object exists before you mark a kind as present.

The deadline job sends a due_soon notice a day or two before due_by for cases still in needs_response, and after due_by it marks cases still in needs_response as expired. A case already in submitting stays in that state so delivery can be retried and a late provider outcome can still be recorded. FOR UPDATE SKIP LOCKED lets two overlapping runs split the work without expiring the same row twice.

UPDATE disputes SET status = 'expired' WHERE id = ( SELECT id FROM disputes WHERE status = 'needs_response' AND due_by <= now() ORDER BY due_by LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING id, charge_id;

Do not auto-submit an incomplete package to beat the clock. Stripe documents that the response is final once it is submitted, so a thin package sent in the last hour cannot be amended later. Accepting the dispute is the safer choice when required evidence is still missing.

How Do You Build It by Hand on AWS?

The design above does not depend on a particular application framework. A service you build and operate yourself on AWS can implement every part of it.

  1. Store disputes. RDS for PostgreSQL holds the schema, and the API runs on ECS Fargate in private subnets that can reach the database. You write the task role, the security groups and the DATABASE_URL (or a secrets-backed equivalent), and you apply migrations as a step in the deploy.
  2. Ingest provider events. An HTTPS endpoint verifies a signature over the raw body, writes to processed_events, and opens or closes a dispute. You terminate TLS, rotate the webhook secret in Secrets Manager and inject it into the task. Stripe delivers charge.dispute.created and charge.dispute.closed to an event destination when that destination is configured.
  3. Collect evidence. A private S3 bucket with public access blocked holds the files. The API returns presigned PUT URLs valid for minutes, checks with HeadObject that each required kind arrived, and then sets evidence_ready. The task role needs write access to that bucket, and you maintain the bucket policy.
  4. Submit once. A reviewer endpoint runs the conditional UPDATE, then calls the provider with an idempotency key and signed download URLs, or with the file bytes the provider expects. The provider key lives in Secrets Manager.
  5. Sweep deadlines. An EventBridge Scheduler rule, or an ECS scheduled task, runs every hour, sends due_soon notices and marks overdue cases expired.
  6. Notify. Opened, due soon, submitted, expired and closed notices go to SNS, and a worker on an SQS queue sends each one once, keyed by dispute and kind, which is what sent_notices enforces.

You also write the Dockerfile, the load balancer and the deployment pipeline. This path is explicit and portable, and the connecting work (IAM, networking, secret injection, the scheduler and the deploy graph) stays yours to keep in sync with the case rules as they grow.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure for TypeScript and Go. The disputes database, the evidence bucket, the notices topic, the deadline job and the provider secrets are declared in the service code. When the app deploys to your own AWS account, Encore provisions RDS, S3, SNS, SQS and Secrets Manager, as the AWS infrastructure docs list. The same code deploys to GCP with Cloud SQL, Cloud Storage, Pub/Sub and Secret Manager. Encore provisions an IAM role for the service, or a service account on GCP. Pave Bank built a licensed bank on Encore and kept full control of its own cloud environment in GCP, and Echo built its Go backend on Encore and deployed it to its own cloud on AWS. This article does not claim those teams shipped this exact flow. Talk to your compliance team about any card-network rules that apply to you.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

A coding agent working in this repository adds a table, a bucket or a topic in the same change as the handler, and encore run starts Postgres locally and stores objects on disk so intake, upload and submit can be called before anything is pushed. Cron jobs do not run in local development or preview environments, so the deadline sweep is tested by calling its endpoint from the local dashboard.

Set Up the App

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create payments --example=hello-world$ cd payments && mkdir -p disputes/migrations$ encore secret set --type prod,dev,local PspWebhookSecret$ encore secret set --type prod,dev,local PspApiKey

Secret values stay out of the repository, where a coding agent working in the code sees the secret's name but not its value, and each environment gets its own webhook secret and provider key. Put the schema from the data model section in disputes/migrations/1_disputes.up.sql.

Intake, Evidence and Submit

The handlers below open a dispute once, issue signed upload URLs, mark required evidence present, and submit with a conditional UPDATE plus an idempotency key. Deadline notices and expiry follow in the same package.

// disputes/disputes.go package disputes import ( "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "io" "net/http" "time" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/rlog" "encore.dev/storage/objects" "encore.dev/storage/sqldb" "encore.dev/pubsub" ) var secrets struct { PspWebhookSecret string PspApiKey string } var db = sqldb.NewDatabase("disputes", sqldb.DatabaseConfig{Migrations: "./migrations"}) var evidence = objects.NewBucket("dispute-evidence", objects.BucketConfig{Versioned: true}) type Notice struct { Kind string // opened, due_soon, submitted, expired, closed DisputeID string ChargeID string } var Notices = pubsub.NewTopic[*Notice]("dispute-notices", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type pspEvent struct { ID string `json:"id"` Type string `json:"type"` Dispute struct { ID string `json:"id"` Charge string `json:"charge"` Amount int `json:"amount"` Currency string `json:"currency"` Reason string `json:"reason"` Status string `json:"status"` DueBy int64 `json:"due_by"` } `json:"dispute"` } //encore:api public raw method=POST path=/webhooks/psp func PspWebhook(w http.ResponseWriter, req *http.Request) { body, err := io.ReadAll(io.LimitReader(req.Body, 1<<20)) if err != nil { http.Error(w, "bad body", http.StatusBadRequest) return } mac := hmac.New(sha256.New, []byte(secrets.PspWebhookSecret)) mac.Write(body) if !hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(req.Header.Get("X-Psp-Signature"))) { http.Error(w, "bad signature", http.StatusUnauthorized) return } var ev pspEvent if err := json.Unmarshal(body, &ev); err != nil { http.Error(w, "bad json", http.StatusBadRequest) return } if err := handleEvent(req.Context(), ev); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } func handleEvent(ctx context.Context, ev pspEvent) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() res, err := tx.Exec(ctx, ` INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, ev.ID) if err != nil { return err } n, _ := res.RowsAffected() if n == 0 { return nil } switch ev.Type { case "charge.dispute.created": _, err = tx.Exec(ctx, ` INSERT INTO disputes (id, charge_id, amount_cents, currency, reason, status, due_by) VALUES ($1, $2, $3, $4, $5, 'needs_response', to_timestamp($6)) ON CONFLICT (id) DO NOTHING`, ev.Dispute.ID, ev.Dispute.Charge, ev.Dispute.Amount, ev.Dispute.Currency, ev.Dispute.Reason, ev.Dispute.DueBy) if err != nil { return err } if err := tx.Commit(); err != nil { return err } _, err = Notices.Publish(ctx, &Notice{Kind: "opened", DisputeID: ev.Dispute.ID, ChargeID: ev.Dispute.Charge}) return err case "charge.dispute.closed", "charge.dispute.updated": res, err = tx.Exec(ctx, ` UPDATE disputes SET status = $2 WHERE id = $1 AND status IN ('submitting', 'submitted', 'under_review', 'needs_response') AND $2 IN ('under_review', 'won', 'lost')`, ev.Dispute.ID, ev.Dispute.Status) if err != nil { return err } applied, _ := res.RowsAffected() if applied == 0 { var status string if err := tx.QueryRow(ctx, `SELECT status FROM disputes WHERE id = $1`, ev.Dispute.ID).Scan(&status); err != nil { return err } if status == "submitting" { return errs.B().Code(errs.Internal).Msg("outcome not applied while submitting").Err() } } if err := tx.Commit(); err != nil { return err } if ev.Type == "charge.dispute.closed" { _, err = Notices.Publish(ctx, &Notice{Kind: "closed", DisputeID: ev.Dispute.ID, ChargeID: ev.Dispute.Charge}) } return err } return tx.Commit() } type UploadResponse struct { URL string } //encore:api private method=POST path=/disputes/:id/files/:kind func SignedUpload(ctx context.Context, id, kind string) (*UploadResponse, error) { var status string err := db.QueryRow(ctx, `SELECT status FROM disputes WHERE id = $1`, id).Scan(&status) if err != nil { return nil, err } if status != "needs_response" { return nil, errs.B().Code(errs.FailedPrecondition).Msg("files are locked after submit").Err() } key := id + "/" + kind u, err := evidence.SignedUploadURL(ctx, key, objects.WithTTL(15*time.Minute)) if err != nil { return nil, err } return &UploadResponse{URL: u.URL}, nil } //encore:api private method=POST path=/disputes/:id/files/:kind/confirm func ConfirmFile(ctx context.Context, id, kind string) error { key := id + "/" + kind ok, err := evidence.Exists(ctx, key) if err != nil { return err } if !ok { return errs.B().Code(errs.FailedPrecondition).Msg("object not uploaded").Err() } _, err = db.Exec(ctx, ` INSERT INTO evidence_files (dispute_id, kind, object_key) VALUES ($1, $2, $3) ON CONFLICT (dispute_id, kind) DO UPDATE SET object_key = EXCLUDED.object_key`, id, kind, key) if err != nil { return err } // Example policy: a receipt is always required. Extend per reason code. _, err = db.Exec(ctx, ` UPDATE disputes SET evidence_ready = TRUE WHERE id = $1 AND EXISTS ( SELECT 1 FROM evidence_files WHERE dispute_id = $1 AND kind = 'receipt' )`, id) return err } //encore:api private method=POST path=/disputes/:id/submit func Submit(ctx context.Context, id string) error { return deliverSubmission(ctx, id) } // deliverSubmission claims the case as submitting, calls the provider, and only // then marks it submitted. A later run retries rows left in submitting. func deliverSubmission(ctx context.Context, id string) error { var chargeID string err := db.QueryRow(ctx, ` UPDATE disputes SET status = 'submitting' WHERE id = $1 AND status IN ('needs_response', 'submitting') AND evidence_ready AND (due_by > now() OR status = 'submitting') RETURNING charge_id`, id).Scan(&chargeID) if err != nil { return errs.B().Code(errs.FailedPrecondition).Msg("cannot submit this dispute").Err() } if err := sendPackage(ctx, id); err != nil { return err } _, err = db.Exec(ctx, ` UPDATE disputes SET status = 'submitted', submitted_at = now() WHERE id = $1 AND status = 'submitting'`, id) if err != nil { return err } _, err = Notices.Publish(ctx, &Notice{Kind: "submitted", DisputeID: id, ChargeID: chargeID}) return err } func sendPackage(ctx context.Context, id string) error { // Build short-lived signed download URLs and POST them to the provider // with Idempotency-Key: dispute-<id>. Retry deliverSubmission if the HTTP // call fails; the row stays in submitting until delivery is confirmed. _ = secrets.PspApiKey _ = ctx _ = id return nil } type expiredRow struct { ID string ChargeID string } //encore:api private method=POST path=/disputes/sweep func SweepDeadlines(ctx context.Context) error { // Retry submissions that claimed a case but did not finish delivery. for i := 0; i < 200; i++ { var id string err := db.QueryRow(ctx, ` SELECT id FROM disputes WHERE status = 'submitting' ORDER BY submitted_at NULLS FIRST LIMIT 1 FOR UPDATE SKIP LOCKED`).Scan(&id) if err == sqldb.ErrNoRows { break } if err != nil { return err } if err := deliverSubmission(ctx, id); err != nil { return err } } for i := 0; i < 200; i++ { var row expiredRow err := db.QueryRow(ctx, ` UPDATE disputes SET status = 'expired' WHERE id = ( SELECT id FROM disputes WHERE status = 'needs_response' AND due_by <= now() ORDER BY due_by LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING id, charge_id`).Scan(&row.ID, &row.ChargeID) if err == sqldb.ErrNoRows { break } if err != nil { return err } if _, err := Notices.Publish(ctx, &Notice{Kind: "expired", DisputeID: row.ID, ChargeID: row.ChargeID}); err != nil { return err } } // due_soon: disputes still in needs_response with due_by within 48 hours, // inserted into sent_notices so each case is warned once. return nil } var _ = cron.NewJob("sweep-dispute-deadlines", cron.JobConfig{ Title: "Warn and expire chargeback deadlines", Every: 1 * cron.Hour, Endpoint: SweepDeadlines, }) var _ = pubsub.NewSubscription(Notices, "email-ops", pubsub.SubscriptionConfig[*Notice]{ Handler: func(ctx context.Context, n *Notice) error { res, err := db.Exec(ctx, ` INSERT INTO sent_notices (dispute_id, kind) VALUES ($1, $2) ON CONFLICT DO NOTHING`, n.DisputeID, n.Kind) if err != nil { return err } rows, _ := res.RowsAffected() if rows == 0 { return nil } rlog.Info("dispute notice", "kind", n.Kind, "dispute", n.DisputeID) return nil }, })

The webhook is a raw endpoint so the HMAC can be checked against the exact bytes the provider sent. The object storage docs cover signed URLs and Exists, the database docs cover migrations and transactions, and the cron job docs cover schedules. encore run starts Postgres locally and stores evidence on disk. Cron jobs do not run locally or in preview environments, so during development you call SweepDeadlines from the local development dashboard. Once deployed, the Encore platform calls it every hour.

Deploy to Your AWS Account

Connect your AWS account as described in Connect your cloud account, create an environment and run git push encore. Encore builds the Docker image, so you do not maintain a Dockerfile. When a coding agent later adds a required evidence kind for a new reason code, the change is a query in ConfirmFile and it reaches production through the same review and deploy as any other pull request.

Things to Decide Early

  • Required evidence per reason. A product-not-received case needs shipping documents that a credit-not-processed case does not. Encode that map in evidence_ready, and do not submit a thin package to beat the clock.
  • Who may submit. Representment is a one-way door, so the submit endpoint should be limited to a payments role, not to every support inbox that can upload a receipt.
  • Auto-accept rules. Low-value disputes are sometimes cheaper to accept than to fight. If you add that path, use the same conditional UPDATE shape as submit, and never auto-submit and auto-accept from two jobs at once.
  • Publishing after commit. The code publishes notices after the transaction commits, so a crash between the two loses one email but never sends one for a rolled-back change. A transactional outbox table removes that gap if every email must go out.

Frequently asked questions

What happens if you miss a chargeback deadline?

You lose the dispute automatically and you cannot retrieve the disputed funds. Stripe's responding guide states that the window is usually 7 to 21 days depending on the card network, and that a missing response is treated as a loss.

Can you change evidence after it is submitted?

No. Stripe documents that the response is final once it is submitted: you cannot amend it or add files afterwards. Build the package, review it, and only then flip the dispute to submitted with a single conditional UPDATE.

How do you store chargeback evidence files safely?

Keep them in a private, versioned bucket and give case owners short-lived signed upload and download URLs, rather than making objects public or proxying the files through the API. Record each file kind once per dispute, and refuse submission until the kinds your policy requires are present.

How do you build a chargeback evidence backend with Encore?

Declare the database, the evidence bucket, the notices topic, the deadline job and the provider secrets in the service code. When the app deploys to your own AWS or GCP account, Encore provisions the database, the bucket, the topic and the job, and Encore provisions an IAM role for the service, or a service account on GCP.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders