Scenario C · Cloud and SaaS

Deploying and Configuring a Cloud Service

A developer deploys a webhook relay from the command line, configures it with one file and three environment variables, and verifies a delivery. The scenario shows a developer guide with prerequisites, code and placeholders, a configuration reference, a troubleshooting article, and an explainer of how the service works.

Demonstration scenario. Lattice Cloud and Lattice Relay, a managed webhook relay, are examples created for this portfolio, as are every person, address and figure in these documents. They aren't operating instructions or vendor documentation.

Skills shown
Developer guide, Prerequisites, Configuration, Code examples, Environment variables with placeholders, Verification, Troubleshooting, Technical reference
Documents
Developer guide · Technical reference · Troubleshooting · Explainer

Made from It in the Studio

The Documents

Developer guide

Deploy a Webhook Relay on Lattice Cloud

ID DG-RELAY-101 · version 3.0 · Published · owner: Developer documentation

Set up a Lattice Relay that receives webhooks from a third party, verifies them, and forwards them to your application with retries. You create the project, write one configuration file, set three environment variables, deploy from the command line, and send a test event. Allow twenty minutes. Fictional sample written for this portfolio: Lattice Cloud and Lattice Relay are invented for it.

Before You Start

  • A Lattice Cloud account with the Developer role in the project you deploy to.
  • The lattice command-line tool, version 2.3 or later. Check with lattice --version.
  • Node.js 20 or later, for the local test client.
  • An HTTPS endpoint in your application that accepts POST requests. The guide calls it the target.
  • The signing secret of the third party that sends the webhooks, if it signs them.

Create the Project

  1. Sign in from the command line.
    lattice auth login
  2. Create a project in the region nearest to your target. The project name becomes part of the relay's address, so choose a short one.
    lattice projects create orders-relay --region eu-west-2
  3. Make it the default project for the commands that follow.
    lattice config set project orders-relay

Write the Configuration

Create a file named relay.yaml in an empty folder. The example forwards every event to one target, retries for an hour, and keeps failed deliveries for a week.

version: 1
name: orders-relay
source:
  path: /hooks/orders          # the path the third party posts to
  verify: hmac-sha256          # how incoming events are checked
  secret_from: RELAY_SOURCE_SECRET
targets:
  - name: app
    url_from: RELAY_TARGET_URL
    timeout_seconds: 10
retry:
  max_attempts: 8              # about an hour with exponential backoff
  backoff: exponential
dead_letter:
  keep_days: 7

The file names the environment variables that hold the secret and the target URL, and never the values. The values live in the project's environment, so that the file can be committed.

Set the Environment Variables

Set the three variables with placeholders replaced by your own values. The command stores them encrypted in the project and shows them to nobody afterwards, including you.

lattice env set RELAY_TARGET_URL=<https://your-app.example/webhooks/orders>
lattice env set RELAY_SOURCE_SECRET=<the third party's signing secret>
lattice env set RELAY_API_KEY=<an API key from the console, Developer role>
VariableWhat it holdsExample shape
RELAY_TARGET_URLThe HTTPS address of your targethttps://api.example.com/webhooks/orders
RELAY_SOURCE_SECRETThe secret the third party signs events with32 or more random characters
RELAY_API_KEYThe key the relay uses to report delivery status to the consoleBegins with lk_live_

Caution: Don't put a secret in relay.yaml, in a shell history that is synced, or in a ticket. If a secret leaks, rotate it in the third party's console and run lattice env set again. The relay picks up the new value at the next deployment.

Deploy

  1. From the folder that holds relay.yaml, deploy.
    lattice deploy
  2. Wait for the command to print the relay's address. It has the shape https://orders-relay.eu-west-2.relay.lattice.example/hooks/orders.
  3. Give that address to the third party as the webhook URL.

Verify

  1. Check that the relay is healthy.
    curl -i https://orders-relay.eu-west-2.relay.lattice.example/healthz

    The response is 200 OK with the body {"status":"ok","version":"1"}.

  2. Send a signed test event with the local test client. It signs the body with the source secret the same way the third party does.
    npx @lattice/relay-test send --path /hooks/orders --body '{"order":"test-001"}'
  3. Watch the delivery reach your target.
    lattice deliveries list --last 1

    The delivery shows the state delivered, the target's response code, and the time it took.

Check That It Worked

Your application received one POST with the body {"order":"test-001"} and two added headers: Relay-Delivery-Id, which is unique per event, and Relay-Signature, which your application can verify with the same secret. In the console, the project's Deliveries page shows the event as Delivered with one attempt.

If the state is retrying or failed, see DG-RELAY-103, Deliveries fail or stay in retrying.

Next Steps

  • Read DG-RELAY-102, the configuration reference, for every key in relay.yaml and the limits of a project.
  • Add a second target to fan out one event to two applications. Each target retries on its own.

Download the Markdown

Technical reference

Lattice Relay Configuration Reference

ID DG-RELAY-102 · version 3.0 · Published · owner: Developer documentation

Every key of relay.yaml, the commands of the lattice tool that manage a relay, the states a delivery goes through, and the limits of a project. Fictional sample written for this portfolio.

The Configuration File

relay.yaml is read at deployment. A key that isn't listed here makes the deployment fail with unknown key, so a typo can't silently do nothing.

Top Level

KeyTypeRequiredMeaning
versionintegerYesThe format of the file. Only 1 exists.
namestringYesThe relay's name. Lowercase letters, digits, and hyphens, up to 40 characters.
sourceobjectYesWhere events come in. See source.
targetslistYesWhere events go. One to five entries. See targets.
retryobjectNoHow failed deliveries are retried. See retry.
dead_letterobjectNoWhat happens to deliveries that run out of attempts. See dead_letter.

Source

KeyTypeDefaultMeaning
pathstring/hooksThe path the sender posts to. Must start with /.
verifystringnoneHow incoming events are checked: none, hmac-sha256, or basic.
secret_fromstringThe environment variable that holds the secret for hmac-sha256, or the user:password pair for basic.
signature_headerstringX-Signature-256The header the sender puts the signature in.
max_body_kbinteger256The largest body the relay accepts. Larger bodies get 413 Payload Too Large.

Targets

Each entry in targets is one destination. The relay delivers every event to every target, and keeps a separate attempt count for each.

KeyTypeDefaultMeaning
namestringA label that appears in delivery listings. Unique within the file.
url_fromstringThe environment variable that holds the target's HTTPS address.
timeout_secondsinteger10How long the relay waits for the target's response. 1 to 30.
headersmapExtra headers to send with every delivery. Values may name an environment variable as ${NAME}.
success_codeslist[200, 201, 202, 204]The response codes that count as delivered.

Retry

KeyTypeDefaultMeaning
max_attemptsinteger5Attempts per target, including the first. 1 to 12.
backoffstringexponentialexponential doubles the wait from 5 seconds; fixed waits interval_seconds each time.
interval_secondsinteger30The wait for fixed backoff.
retry_onlist[408, 429, 500, 502, 503, 504]The response codes that lead to a retry. Any other failure code ends the delivery.

dead_letter

KeyTypeDefaultMeaning
keep_daysinteger3How long a failed delivery is kept for replay. 0 to 30.
notify_fromstringAn environment variable with an email address to notify when a delivery fails for good.

Commands

CommandWhat it does
lattice deployReads relay.yaml in the current folder and deploys it to the default project.
lattice env set NAME=valueStores an environment variable, encrypted. Takes effect at the next deployment.
lattice env listLists variable names and when each was last set. Never shows values.
lattice deliveries list [--last N] [--state STATE]Lists deliveries, newest first.
lattice deliveries show IDShows one delivery: every attempt, response code, and duration.
lattice deliveries replay IDSends a delivery again from the dead-letter store.
lattice logs --followStreams the relay's log.

Delivery States

StateMeaningWhat to do
receivedThe event passed verification and is queued.Nothing. It moves on within a second.
deliveredA target returned a success code.Nothing.
retryingA target failed with a retryable code, and another attempt is scheduled.Check the target if it stays here for more than a few minutes.
failedThe attempts ran out, or the target returned a code that isn't retried.Fix the target, and then replay the delivery.
rejectedThe event failed verification, or the body was too large.Check the sender's secret and body size. Rejected events aren't stored.

Response Codes the Relay Returns to the Sender

CodeMeaning
202 AcceptedThe event is queued. The sender should treat this as success.
401 UnauthorizedThe signature or credentials didn't match.
404 Not FoundThe path doesn't match source.path.
413 Payload Too LargeThe body exceeds max_body_kb.
429 Too Many RequestsThe project is over its rate limit. The response carries a Retry-After header.

Limits

LimitDeveloper planTeam plan
Events per minute, per project6006,000
Targets per relay25
Body size256 KB1 MB
Dead-letter retention3 days30 days
Relays per project320

Download the Markdown

Troubleshooting

Deliveries Fail or Stay in Retrying

ID DG-RELAY-103 · version 3.0 · Published · owner: Developer documentation

Events reach the relay, but your application doesn't get them, or gets them late. Start with lattice deliveries show on one affected delivery: its last attempt names the cause in almost every case. Fictional sample written for this portfolio.

What You See

  • lattice deliveries list shows deliveries in the state retrying for more than a few minutes, or in failed.
  • The sender reports 401 Unauthorized from the relay's address.
  • Your application receives the same event twice.

Why It Happens

What the last attempt saysCause
connect: timeout or connect: refusedThe target address is wrong, the target is down, or a firewall in front of it doesn't allow the relay's addresses.
502 or 503 from the targetThe target is overloaded or restarting. The relay retries these on its own.
401 or 403 from the targetThe target expects a credential the relay doesn't send.
signature mismatch on an attempt to your targetYour application verifies Relay-Signature with a different secret from the one the relay signs with.
rejected: signature mismatch on the incoming eventThe secret in RELAY_SOURCE_SECRET differs from the one the sender signs with, or the sender signs a different header.
The same event delivered twiceThe target took longer than timeout_seconds to answer the first time, so the relay sent it again.

Fix It

The Target Can't Be Reached

  1. From a machine outside your network, request the target's address with curl -i. If it fails there too, the problem is the target, not the relay.
  2. If it succeeds, allow the relay's outbound addresses in your firewall. lattice info lists them for your region.
  3. Replay one delivery, and then watch it.
    lattice deliveries replay <delivery id>
    lattice deliveries show <delivery id>

The Target Rejects the Relay

  1. Add the credential the target expects as a header in relay.yaml, with the value in an environment variable.
    targets:
      - name: app
        url_from: RELAY_TARGET_URL
        headers:
          Authorization: "Bearer ${RELAY_TARGET_TOKEN}"
  2. Set the variable, and then deploy again.
    lattice env set RELAY_TARGET_TOKEN=<the token your application expects>
    lattice deploy

Signatures Don't Match

  1. Confirm which secret each side uses. The relay verifies incoming events with RELAY_SOURCE_SECRET, and signs outgoing deliveries with the project's delivery secret, shown once under Settings > Signing in the console.
  2. In your application, verify Relay-Signature with the delivery secret, not with the sender's secret. The two are different on purpose, so that a leaked sender secret can't forge deliveries.
  3. Compute the signature over the raw request body, before any JSON parsing. A parser that reorders keys changes the bytes.

Duplicate Deliveries

  1. Make your handler idempotent: store Relay-Delivery-Id and ignore an id you have already processed.
  2. Answer 202 as soon as you have stored the event, and do the work afterwards. A target that answers within a second is never retried for a timeout.
  3. If the work can't be deferred, raise timeout_seconds to at most 30.

If None of This Fixes It

Collect the delivery id, the output of lattice deliveries show, and the time of the attempt in UTC. Open a ticket with the Lattice Relay support team from the console's Help menu, and include the three items. The team can see the relay's side of each attempt but not your target's logs, so attach those too.

Download the Markdown

Explainer

How Lattice Relay Delivers a Webhook

ID DG-RELAY-100 · version 3.0 · Published · owner: Developer documentation

A webhook is a POST request that a third party sends to you when something happens on their side. If your application is down for a minute, the event is lost, and most senders won't try again. Lattice Relay sits between the sender and your application. It accepts every event at once, and delivers it to you as many times as it takes. This page explains what happens to an event from the moment it arrives. Fictional sample written for this portfolio.

The Five Stages

  1. Receive. The sender posts to the relay's address. The relay reads the body, up to the configured size, and answers 202 Accepted within a few milliseconds. From the sender's point of view, the event is done.
  2. Verify. Before it answers, the relay checks the event the way you configured: an HMAC signature over the body, a username and password, or nothing. An event that fails the check gets 401 and isn't stored. This keeps forged events out of your queue.
  3. Queue. The event is written to the project's durable queue in the region you chose, with a unique delivery id for each target. The queue survives a restart of the relay.
  4. Deliver. A worker takes the event from the queue and posts it to each target with the original body. It adds two headers: the delivery id, and a signature made with your project's delivery secret.
  5. Retry or settle. A success code settles the delivery. A retryable failure schedules another attempt after a wait that doubles each time, from five seconds to about seventeen minutes. When the attempts run out, the delivery moves to the dead-letter store, where you can inspect and replay it.

Why the Relay Answers Before It Delivers

Senders give a webhook a few seconds to answer, and some disable an endpoint after a handful of timeouts. If the relay waited for your application, a slow response on your side would count against you with the sender. Answering 202 first makes your availability your own concern, and the queue's job.

At Least Once, Not Exactly Once

The relay guarantees that every verified event reaches every target at least once. It can't guarantee exactly once: if your application processes an event but the response is lost on the network, the relay doesn't know and sends the event again. Your handler should therefore remember the delivery ids it has processed, and answer 202 without doing the work a second time.

Two Secrets, Two Directions

SecretWho knows itWhat it proves
Source secretThe sender and the relayThat an incoming event came from the sender.
Delivery secretThe relay and your applicationThat an outgoing delivery came from your relay.

They're separate so that a leak of one doesn't compromise the other direction. If the sender's secret leaks, an attacker can post to the relay, but can't forge a delivery to your application with a valid Relay-Signature.

Ordering

Events from one sender are delivered in the order they arrived, as long as every delivery succeeds at the first attempt. A retry doesn't hold back the events behind it: a delivery that is retrying may arrive after a newer one. If order matters to your application, use the event's own timestamp, not the arrival order.

What the Relay Keeps, and for How Long

DataKept for
Event bodies in the queueUntil delivered or failed
Failed deliveries in the dead-letter storedead_letter.keep_days, 3 by default
Delivery metadata: ids, attempts, response codes, durations30 days
Environment variablesUntil you change them, encrypted at rest

Nothing is kept outside the region of the project.

Download the Markdown