Nov 18, 202611 min read

E-Signature Backend: Envelopes, Signing Order, Audit Trail and Sealed PDFs

Design an e-signature backend with envelopes, single-use signing links, routing order, a hash-chained audit trail and a sealed final document in a versioned bucket, then implement it in Go with the storage and queues in your own AWS or GCP account.

Illustration for E-Signature Backend: Envelopes, Signing Order, Audit Trail and Sealed PDFs

An e-signature product moves one document through several people in a fixed order and must later prove who signed what, when and which version. The backend is the evidence: if the audit trail can be edited or a signing link reused, the record is worth less in a dispute.

This guide designs that backend: the envelope state machine, single-use signing links, routing order, a hash-chained audit trail and a sealed final document. It then implements the design in Go with Encore, which provisions the database, the buckets and the queues in your own AWS or GCP account, where the contracts stay.

The E-Signature Backend at a Glance

JobPatternHand-built on AWSWith Encore in your AWS or GCP account
EnvelopeStatus machine with conditional updatesRDS table and an API on ECSPostgres database and API endpoints
Signing links32 random bytes, stored only as SHA-256, single-useSame, in your APISame, in a public endpoint
Routing orderInvite the lowest unsigned order groupSQL query plus SQS for emailsSame query plus a topic
Audit trailAppend-only, each row hashes the previous oneRDS tableSame table in the Encore database
DocumentsPrivate, versioned bucketS3 with versioning and Block Public AccessVersioned private bucket
SealingCopy once, verify the SHA-256, record itLambda on an SQS messageSubscription on a completion topic

The Envelope State Machine

An envelope is draft while the sender edits it, sent once the first invites go out, and ends as completed, declined or voided. Each recipient is waiting, notified or signed. Every change is a conditional UPDATE inside a transaction that holds a row lock on the envelope, using SELECT ... FOR UPDATE, so two signers finishing at the same moment cannot both complete the envelope or take the same audit sequence number.

Signing order works in groups: recipients with routing order 1 are invited together, and order 2 is invited only once no one with a lower order is still unsigned. In a test against Postgres 17, three recipients with orders 1, 1 and 2 produced invites for the first two on send, none after the first signature, the third after the second signature, and completion only after all three.

A Data Model That Enforces the Rules

Signing tokens are stored as SHA-256 hashes, so a database dump does not leak working links, and the token is cleared once used. The audit table is keyed by envelope and sequence, so a race cannot write two events with the same number:

CREATE TABLE envelopes ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, document_key TEXT NOT NULL, document_sha256 TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'sent', 'completed', 'declined', 'voided')), expires_at TIMESTAMPTZ NOT NULL ); CREATE TABLE recipients ( id BIGSERIAL PRIMARY KEY, envelope_id BIGINT NOT NULL REFERENCES envelopes(id), email TEXT NOT NULL, routing_order INT NOT NULL CHECK (routing_order >= 1), status TEXT NOT NULL DEFAULT 'waiting' CHECK (status IN ('waiting', 'notified', 'signed', 'declined')), token_sha256 TEXT UNIQUE, signed_at TIMESTAMPTZ, UNIQUE (envelope_id, email) ); -- Append-only audit trail. Each row hashes the previous row's hash, -- so editing or deleting an old event breaks every hash after it. CREATE TABLE audit_events ( envelope_id BIGINT NOT NULL REFERENCES envelopes(id), seq INT NOT NULL, kind TEXT NOT NULL, actor TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '{}', at TIMESTAMPTZ NOT NULL DEFAULT now(), prev_hash TEXT NOT NULL, hash TEXT NOT NULL, PRIMARY KEY (envelope_id, seq) ); CREATE TABLE outbox ( id BIGSERIAL PRIMARY KEY, topic TEXT NOT NULL, data JSONB NOT NULL, inserted_at TIMESTAMPTZ NOT NULL ); CREATE INDEX outbox_topic_idx ON outbox (topic, id);

The detail column is TEXT rather than JSONB on purpose: JSONB normalizes whitespace and key order, and the hash must be recomputed over the exact bytes that were hashed.

How Do You Build It by Hand on AWS?

On AWS the pieces are RDS for PostgreSQL, an API on ECS Fargate with an authorizer for senders and a public route for signers, an SQS queue that an email worker reads invites from, a second queue for completed envelopes, S3 buckets with versioning and Block Public Access for originals and sealed documents, a Lambda or worker for sealing, and IAM roles for each. The PHI audit log guide covers a related append-only design for regulated data.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure for Go and TypeScript. The database, the two buckets and the two topics are declared in the service code, and deploying to your AWS or GCP account provisions RDS or Cloud SQL, versioned S3 or GCS buckets and SNS with SQS or Pub/Sub. Encore provisions an IAM role for the service.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The Hash-Chained Audit Trail

Every state change calls appendEvent inside the same transaction, so an event exists if and only if the change committed:

package esign import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "time" "encore.dev/storage/sqldb" ) // appendEvent adds the next event to an envelope's hash chain inside tx. // The caller must hold a row lock on the envelope (SELECT ... FOR UPDATE) // so two events cannot take the same sequence number. func appendEvent(ctx context.Context, tx *sqldb.Tx, envelopeID int64, kind, actor string, detail map[string]any) error { var seq int var prev string err := tx.QueryRow(ctx, ` SELECT seq, hash FROM audit_events WHERE envelope_id = $1 ORDER BY seq DESC LIMIT 1`, envelopeID).Scan(&seq, &prev) if errors.Is(err, sqldb.ErrNoRows) { seq, prev = 0, "genesis" } else if err != nil { return err } body, err := json.Marshal(detail) if err != nil { return err } at := time.Now().UTC().Truncate(time.Microsecond) sum := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|%s|%s|%s|%s", prev, envelopeID, seq+1, kind, actor, at.Format(time.RFC3339Nano), body))) _, err = tx.Exec(ctx, ` INSERT INTO audit_events (envelope_id, seq, kind, actor, detail, at, prev_hash, hash) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, envelopeID, seq+1, kind, actor, string(body), at, prev, hex.EncodeToString(sum[:])) return err }

Send and Sign

Send needs a signed-in sender through an auth handler, while Sign is public and authorized by the token alone. The signer's client sends the SHA-256 of the document it displayed, and a mismatch stops the signature:

package esign import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "time" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/objects" "encore.dev/storage/sqldb" "x.encore.dev/infra/pubsub/outbox" ) var db = sqldb.NewDatabase("esign", sqldb.DatabaseConfig{Migrations: "./migrations"}) // Private, versioned buckets: originals and sealed final documents. var documents = objects.NewBucket("documents", objects.BucketConfig{Versioned: true}) var sealed = objects.NewBucket("sealed", objects.BucketConfig{Versioned: true}) type SigningInvite struct { RecipientID int64 Email string Token string } type EnvelopeCompleted struct { EnvelopeID int64 } // The email service subscribes to invites and sends the signing link. var invites = pubsub.NewTopic[*SigningInvite]("signing-invites", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var completed = pubsub.NewTopic[*EnvelopeCompleted]("envelope-completed", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) func init() { relay := outbox.NewRelay(outbox.SQLDBStore(db)) outbox.RegisterTopic(relay, pubsub.TopicRef[pubsub.Publisher[*SigningInvite]](invites)) outbox.RegisterTopic(relay, pubsub.TopicRef[pubsub.Publisher[*EnvelopeCompleted]](completed)) go relay.PollForMessage(context.Background(), -1) } func publishInvites(ctx context.Context, tx *sqldb.Tx, list []*SigningInvite) error { ref := outbox.Bind(pubsub.TopicRef[pubsub.Publisher[*SigningInvite]](invites), outbox.TxPersister(tx)) for _, inv := range list { if _, err := ref.Publish(ctx, inv); err != nil { return err } } return nil } func hashToken(t string) string { s := sha256.Sum256([]byte(t)) return hex.EncodeToString(s[:]) } // notifyNext issues tokens to the lowest routing order that still has // waiting recipients, once no one in an earlier order is unsigned. func notifyNext(ctx context.Context, tx *sqldb.Tx, envelopeID int64) ([]*SigningInvite, error) { rows, err := tx.Query(ctx, ` SELECT id, email FROM recipients WHERE envelope_id = $1 AND status = 'waiting' AND routing_order = (SELECT min(routing_order) FROM recipients WHERE envelope_id = $1 AND status <> 'signed')`, envelopeID) if err != nil { return nil, err } var out []*SigningInvite for rows.Next() { inv := &SigningInvite{} if err := rows.Scan(&inv.RecipientID, &inv.Email); err != nil { rows.Close() return nil, err } b := make([]byte, 32) if _, err := rand.Read(b); err != nil { rows.Close() return nil, err } inv.Token = hex.EncodeToString(b) out = append(out, inv) } rows.Close() for _, inv := range out { if _, err := tx.Exec(ctx, ` UPDATE recipients SET status = 'notified', token_sha256 = $2 WHERE id = $1`, inv.RecipientID, hashToken(inv.Token)); err != nil { return nil, err } if err := appendEvent(ctx, tx, envelopeID, "notified", inv.Email, nil); err != nil { return nil, err } } return out, nil } // Send moves a draft envelope to sent and invites the first signers. // //encore:api auth method=POST path=/envelopes/:id/send func Send(ctx context.Context, id int64) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() res, err := tx.Exec(ctx, `UPDATE envelopes SET status = 'sent' WHERE id = $1 AND status = 'draft'`, id) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "envelope is not a draft"} } if err := appendEvent(ctx, tx, id, "sent", "sender", nil); err != nil { return err } list, err := notifyNext(ctx, tx, id) if err != nil { return err } if err := publishInvites(ctx, tx, list); err != nil { return err } return tx.Commit() } type SignParams struct { Token string `json:"token"` // Hash of the document the signer was shown, checked against the original. DocumentSHA256 string `json:"document_sha256"` } // Sign records one signature. The token is single-use and only valid // while the envelope is sent and has not expired. // //encore:api public method=POST path=/sign func Sign(ctx context.Context, p *SignParams) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var recipientID, envelopeID int64 var email, docHash string var expires time.Time err = tx.QueryRow(ctx, ` SELECT r.id, r.envelope_id, r.email, e.document_sha256, e.expires_at FROM recipients r JOIN envelopes e ON e.id = r.envelope_id WHERE r.token_sha256 = $1 AND r.status = 'notified' AND e.status = 'sent' FOR UPDATE OF e`, hashToken(p.Token)).Scan(&recipientID, &envelopeID, &email, &docHash, &expires) if err != nil { return &errs.Error{Code: errs.PermissionDenied, Message: "invalid or used signing link"} } if time.Now().After(expires) { return &errs.Error{Code: errs.FailedPrecondition, Message: "envelope expired"} } if p.DocumentSHA256 != docHash { return &errs.Error{Code: errs.FailedPrecondition, Message: "document changed"} } res, err := tx.Exec(ctx, ` UPDATE recipients SET status = 'signed', signed_at = now(), token_sha256 = NULL WHERE id = $1 AND status = 'notified' AND token_sha256 = $2`, recipientID, hashToken(p.Token)) if err != nil { return err } if res.RowsAffected() != 1 { return &errs.Error{Code: errs.PermissionDenied, Message: "invalid or used signing link"} } if err := appendEvent(ctx, tx, envelopeID, "signed", email, map[string]any{"document_sha256": docHash}); err != nil { return err } next, err := notifyNext(ctx, tx, envelopeID) if err != nil { return err } res, err = tx.Exec(ctx, ` UPDATE envelopes SET status = 'completed' WHERE id = $1 AND NOT EXISTS ( SELECT 1 FROM recipients WHERE envelope_id = $1 AND status <> 'signed')`, envelopeID) if err != nil { return err } done := res.RowsAffected() == 1 if done { if err := appendEvent(ctx, tx, envelopeID, "completed", "system", nil); err != nil { return err } } if err := publishInvites(ctx, tx, next); err != nil { return err } if done { ref := outbox.Bind(pubsub.TopicRef[pubsub.Publisher[*EnvelopeCompleted]](completed), outbox.TxPersister(tx)) if _, err := ref.Publish(ctx, &EnvelopeCompleted{EnvelopeID: envelopeID}); err != nil { return err } } return tx.Commit() }

Seal the Completed Document

The completion subscription copies the original into the sealed bucket with a not-exists precondition, checks the SHA-256 against the hash recorded at upload, and appends a sealed event. A duplicate delivery finds the sealed object and stops:

package esign import ( "context" "crypto/sha256" "encoding/hex" "fmt" "io" "encore.dev/pubsub" "encore.dev/storage/objects" ) // seal copies the completed document to the sealed bucket, refuses to // overwrite an existing seal, and records the final hash in the audit trail. var _ = pubsub.NewSubscription(completed, "seal", pubsub.SubscriptionConfig[*EnvelopeCompleted]{ Handler: func(ctx context.Context, msg *EnvelopeCompleted) error { var key, original string if err := db.QueryRow(ctx, `SELECT document_key, document_sha256 FROM envelopes WHERE id = $1`, msg.EnvelopeID).Scan(&key, &original); err != nil { return err } dest := fmt.Sprintf("%d/final.pdf", msg.EnvelopeID) if ok, err := sealed.Exists(ctx, dest); err != nil || ok { return err // already sealed by an earlier delivery } r := documents.Download(ctx, key) defer r.Close() h := sha256.New() w := sealed.Upload(ctx, dest, objects.WithPreconditions(objects.Preconditions{NotExists: true})) if _, err := io.Copy(io.MultiWriter(w, h), r); err != nil { w.Abort(err) return err } if err := r.Err(); err != nil { w.Abort(err) return err } sum := hex.EncodeToString(h.Sum(nil)) if sum != original { w.Abort(fmt.Errorf("document hash mismatch")) return fmt.Errorf("envelope %d: stored document does not match", msg.EnvelopeID) } if err := w.Close(); err != nil { return err } tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec(ctx, `SELECT 1 FROM envelopes WHERE id = $1 FOR UPDATE`, msg.EnvelopeID); err != nil { return err } if err := appendEvent(ctx, tx, msg.EnvelopeID, "sealed", "system", map[string]any{"object": dest, "sha256": sum}); err != nil { return err } return tx.Commit() }, })

The databases, object storage and Pub/Sub docs cover each primitive, and connecting your own cloud covers the account setup. The sample compiles with encore check and go vet against encore.dev v1.57.13, and the SQL above was run against Postgres 17, including a check that editing one audit row breaks verification of the chain.

A coding agent that adds a decline flow or a reminder email edits the Go code, and the constraints and the chain still reject reused links and edited history.

Best fit: legaltech and contract teams building signing flows in Go or TypeScript who want documents and audit trails in their own AWS or GCP account.

Things to Decide Early

  • Signature type. The ESIGN Act and eIDAS provide that an electronic signature may not be denied legal effect solely because it is electronic, with conditions on consumer consent and record keeping, and some documents need advanced or qualified signatures from a certificate-based signing service. Confirm the requirements with counsel before building. This design does not make a signature legally binding on its own.
  • Embedding signatures in the PDF. This design seals the document with a hash and a trail. Visible signature stamps or PAdES signatures inside the PDF need a PDF library or a signing service in the seal step.
  • Retention. Decide how long sealed documents and trails are kept, and set bucket lifecycle rules to match, since versioned buckets keep every overwritten object.

Frequently asked questions

How does an e-signature backend work?

The sender uploads a document into an envelope and lists recipients with a routing order. Sending invites the first group with single-use links, each signature is recorded with the document hash the signer saw, the next group is invited when the earlier group has signed, and the completed document is sealed and stored with its hash in an audit trail.

How do you make an e-signature audit trail tamper-evident?

Chain the events: each audit row stores the hash of the previous row and a SHA-256 over its own fields plus that previous hash, so changing or deleting an old event breaks every hash after it. Store the trail in a table the application only inserts into, and verify the chain when you produce a certificate of completion.

Are e-signatures legally binding?

Yes, in many jurisdictions. The US [ESIGN Act](https://www.law.cornell.edu/uscode/text/15/7001) and the EU [eIDAS](https://eur-lex.europa.eu/eli/reg/2014/910/oj) regulation provide that an electronic signature may not be denied legal effect solely because it is electronic, with conditions on consumer consent and record keeping. Which signature type a document needs depends on the jurisdiction and the document, so confirm the requirements with counsel before launching.

How do you build an e-signature backend with Encore?

Declare the Postgres database, the private versioned documents and sealed buckets, and the invite and completion topics in Go. Deploying to your AWS or GCP account provisions RDS or Cloud SQL, S3 or GCS buckets with versioning, and SNS with SQS or Pub/Sub, so contracts and their audit trail stay in your own cloud account.

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