Webhooks in Flagsmith
A complete, beginner-friendly guide to how Flagsmith tells the rest of your world that a feature flag has changed: what webhooks are, how they travel, how to secure them, and how to build receivers that never miss a beat.
Picture this. It is two in the morning, and an engineer on call flips a single switch inside a feature flag tool to turn off a shaky new checkout page. The switch works. Customers stop seeing the broken page. But the support team, the analytics team, the security team and the cache servers all keep living as if nothing happened. The support team keeps telling customers about the old behaviour. The cache keeps serving stale answers. Nobody wrote the change down anywhere that matters. A single quiet switch has created a dozen small confusions.
This is the exact problem that webhooks solve. A webhook is a way for one system to knock on another system’s door the moment something interesting happens. In Flagsmith, the open-source feature flag and remote configuration service, webhooks are the knock. Every time a flag changes, Flagsmith can send a small message to any web address you choose, so your other tools can react right away instead of finding out hours later.
In this guide we start from zero. You do not need to know what a webhook is, what a feature flag is, or how Flagsmith is organised. We will explain each new word the first time it appears, use everyday comparisons, and then build up to the advanced topics that production teams care about: signatures, retries, duplicates, ordering, monitoring, and failure recovery. By the end, you will be able to design, secure, operate and troubleshoot Flagsmith webhooks with confidence.
1Why Webhooks Matter in a Feature Flag World
Before we talk about the knock, we need to understand the switch. This chapter explains feature flags, Flagsmith, and the real-world pain that webhooks remove.
What is a feature flag?
A feature flag is a switch inside your software that lets you turn a feature on or off without releasing new code. Instead of writing the rule “show the new checkout page” directly into the program and shipping it, developers write the rule as “show the new checkout page only if the flag called new_checkout is on.” The flag itself lives outside the program, in a tool that can be changed in seconds by a person with a browser.
Think of the lights in a large office building. The wiring is installed once, when the building is built. After that, nobody rewires anything to turn a floor on or off. Someone just flips a switch on a panel. A feature flag is that panel switch for your software. The wiring is the code. The switch is the flag. You can flip it for one floor, for one room, or for the whole building, without calling an electrician.
What is Flagsmith?
Flagsmith is a feature flag and remote configuration service. It is open source, which means anyone can read its code, and you can run it yourself on your own servers or use the hosted version that the Flagsmith team operates. It gives you a dashboard where people manage flags, and it gives your applications a way to ask, “is this flag on for this user right now?” Besides simple on-and-off switches, Flagsmith can store values, such as a text message, a number, or a small piece of configuration, so you can change how an app behaves without redeploying it. That second ability is called remote configuration.
The silent switch problem
Flags are powerful because they change behaviour instantly. That same power creates a risk: changes happen quietly. Without some form of announcement, the rest of your company only finds out about a flag change when something looks different. Consider a few examples of what goes wrong when changes are silent:
- A caching layer holds on to old answers because nobody told it that a flag changed, so some users see the new behaviour while others see the old one.
- A compliance team needs a record of every production change, but the only record lives inside the flag tool itself, where nobody checks.
- A release manager wants a chat message in the team channel whenever a risky flag is switched on in production, but has to ask developers to remember to post it.
- A data team wants to line up flag changes with spikes in error rates, but has no timeline of when each change happened.
Pull versus push
There are two basic ways for a system to learn about a change. In the pull style, the interested system keeps asking, over and over, “Has anything changed?” In the push style, the system where the change happens sends a message the moment it occurs. Webhooks are the push style. Flagsmith pushes a message to your chosen address immediately after a flag change, so you do not have to keep asking.
Webhooks tell other systems that something changed. They are not how your application reads flag values. Your application uses a Flagsmith SDK for that. Webhooks are for everything around your application: alerts, audits, caches, pipelines and reports.
2Webhooks Explained from Zero
If the word webhook has always sounded mysterious, this chapter removes the mystery. A webhook is just a polite, automatic web request.
The web in thirty seconds
Every time you open a website, your browser sends a request to a computer somewhere, and that computer sends back a reply. The address you type is called a URL. The request has a type, called a method. The two methods that matter here are GET, which means “give me something,” and POST, which means “here is something for you.” Replies carry a three-digit status code. Codes that begin with 2, such as 200, mean success. Codes that begin with 4 mean you made a mistake, and codes that begin with 5 mean the other computer had a problem.
So what is a webhook?
A webhook is an automatic POST request that one system sends to a URL you provide, whenever a certain event happens. The message inside the request is usually written in JSON, a simple text format for describing information with names and values. The system that sends the message is the sender. The system that receives it, at the URL you gave, is the receiver. You are the one who builds and hosts the receiver. Flagsmith is the sender.
A webhook is like leaving your phone number with a restaurant host. Instead of standing by the door and asking every two minutes whether your table is ready, you go for a walk. When the table is free, the host calls you. The call is the webhook. Your phone number is the URL. The host is the sender. You are the receiver, and you are free to do other things in between.
Webhooks compared with polling
Polling is the opposite of a webhook. A polling system asks again and again on a timer. Polling is simple, but it has two weaknesses. First, it wastes effort, because most of the time the answer is “nothing new.” Second, it is slow, because a change that happens one second after a check will not be noticed until the next check. Webhooks avoid both weaknesses because the message is sent only when there is something to say, and it is sent right away.
| Question | Polling | Webhook |
|---|---|---|
| Who starts the conversation? | The interested system, repeatedly | The system where the change happens, once per event |
| How fast is the news? | As slow as the timer interval | Within moments of the change |
| How much wasted work? | Lots of empty checks | Almost none |
| What must you run? | A scheduled job | A public web address that listens |
| What can go wrong? | Missed changes between checks | Missed messages if the receiver is down |
Webhooks compared with a regular API
An API is a menu of questions you can ask a service on demand. A webhook is the service volunteering an announcement. Most real systems use both. You might use the Flagsmith API to list all flags on demand, and you might use a webhook to be told when one of them changes. The two work well together, and we will see later how teams combine them to stay safe when a message is lost.
A webhook receiver must be reachable from the sender over the internet or over a network path the sender can use. A receiver that lives only on your laptop or inside a locked-down private network cannot receive messages from a hosted Flagsmith unless you open a safe path to it.
3Flagsmith Vocabulary You Need First
Flagsmith organises everything in layers. Learning the layers makes webhook settings and payloads easy to read.
Flagsmith groups your work in a tree. At the top is the organisation, which usually represents your company. Inside an organisation live projects, which usually represent one product or application. Inside each project live environments, such as development, staging and production. Inside the project you create features, which are your flags and configuration values. Each environment keeps its own state for each feature, so a flag can be on in development and off in production at the same time.
Organisation
The company-wide container. It holds users, teams, billing and the audit trail of everything that happens inside.
Project
One product or application. Features and segments are defined here and shared across the project’s environments.
Environment
A copy of the world, such as staging or production. Each environment has its own keys and its own flag states.
Feature
A flag or a configuration value. It can be a simple on-off switch, or it can carry a value such as text or a number.
Segment
A saved group of users that share a trait, such as “paying customers” or “beta testers.” Flags can behave differently for a segment.
Identity
One specific user known to Flagsmith, identified by an ID your app supplies. A flag can be overridden for one identity.
Audit log
A running diary of who changed what and when, kept at the organisation level for accountability.
Feature state
The current setting of a feature in one environment: whether it is on, what value it holds, and any overrides.
Imagine a chain of coffee shops. The organisation is the chain. A project is one menu, for example the summer drinks menu. An environment is one shop location, such as the test kitchen or the flagship store. A feature is one drink on the menu. The feature state is whether that drink is currently being sold at that particular shop. Segments are customer groups, like loyalty members. Identities are individual customers. The audit log is the manager’s logbook that records every menu change.
Why this matters for webhooks
Webhooks attach to specific layers. One kind attaches to an environment and reports changes to flag states inside that environment. Another kind attaches to the organisation and reports entries written into the audit log. Knowing which layer you care about tells you which kind of webhook to create, which is exactly what the next chapter covers.
4The Two Families of Flagsmith Webhooks
Flagsmith sends webhooks at two different levels. Picking the right one is the first real design decision.
Environment webhooks
An environment webhook belongs to one environment. It fires when something changes in the state of a feature inside that environment. That includes switching a flag on or off, changing its value, adding or editing a segment override, adding or editing an identity override, and deleting the feature. You configure it in the settings page of the environment. If you want to hear about production changes only, you create it on the production environment and leave the others alone.
Organisation webhooks
An organisation webhook belongs to the whole organisation and is tied to the audit log. Whenever Flagsmith writes a new audit log entry, it can notify your receiver. Audit entries cover a wider range of activities than flag state changes, such as creating or editing features, segments and environments, so this kind of webhook gives you a broader view of what people are doing in Flagsmith. You configure it in the organisation settings.
| Aspect | Environment webhook | Organisation webhook |
|---|---|---|
| Where it lives | One environment | The whole organisation |
| What triggers it | A change to a feature state in that environment | A new entry in the audit log |
| Typical event names | Flag updated, flag deleted | Audit log created |
| Best for | Cache refresh, deploy triggers, chat alerts for one environment | Compliance records, security review, company-wide activity feeds |
| Noise level | Lower and focused | Higher and broader |
| Who usually owns the receiver | The application team | Platform, security or compliance teams |
An environment webhook is like a doorbell camera on one house that tells you when someone touches that door. An organisation webhook is like the security desk of the entire apartment complex that logs every entry, every package and every visitor. Both are useful. You choose based on how wide a view you need.
Many teams start with one environment webhook on production and one organisation webhook for the audit feed. That small pair covers day-to-day alerting and long-term accountability without much noise.
Webhooks are not the same as integrations
Flagsmith also offers built-in integrations with popular tools, for example chat, monitoring and analytics products. An integration is a ready-made connection where Flagsmith already knows how to talk to the other product. A webhook is a general-purpose, do-it-yourself connection that you can point anywhere. If a built-in integration exists for your tool and it does what you need, it can save you work. If not, or if you need custom logic, a webhook is the flexible choice. We compare these options in more detail later.
5Architecture and Components
Let us look at the moving parts that take a click in the dashboard and turn it into a message at your door.
flowchart LR
A["Admin using Dashboard"] --> B["Flagsmith API"]
A2["Automation using Admin API"] --> B
B --> C["Primary Database"]
B --> D["Audit Log Writer"]
B --> E["Background Task Queue"]
D --> C
E --> F["Webhook Dispatcher"]
F --> G["Environment Webhook Receiver"]
F --> H["Organisation Webhook Receiver"]
G --> I["Cache Refresh Service"]
G --> J["Chat Alert Service"]
H --> K["Compliance Archive"]
H --> L["Security Monitoring"]
Walking through the diagram
The diagram reads from left to right. Changes begin at the left, either because a person uses the dashboard or because an automation script calls the Flagsmith admin interface. Both paths end up at the Flagsmith API, which is the front door of the service.
The API does three things when it accepts a change. It saves the new state in the primary database, which is the permanent storage. It asks the audit log writer to record who made the change, what changed and when. And it places work orders on a background task queue. A queue is simply a waiting line for jobs. The important idea is that sending webhooks is placed on the queue instead of being done on the spot, so the person who clicked the switch does not have to wait for the slowest receiver on earth.
A worker picks jobs from the queue and hands them to the webhook dispatcher. The dispatcher looks up which webhooks apply, builds the message, signs it if a secret is configured, and sends the POST request to each receiver. Your receivers then pass the information to the tools that actually care: a cache service, a chat room, a compliance archive or a security monitor.
The components in plain words
Flagsmith API
Accepts changes, checks permissions, saves state and starts the chain of side effects such as audit entries and webhooks.
Primary database
The source of truth for flags, environments, webhook settings and audit entries. Webhook definitions live here too.
Audit log writer
Creates the diary entry for each change. Organisation webhooks are triggered by new entries.
Task queue
Holds webhook jobs so they run in the background, away from the person who made the change.
Webhook dispatcher
Builds the message, applies the signature and sends the request. It also decides when to retry after a failure.
Receiver
The web address you operate. It checks the message, saves it safely and answers quickly with a success code.
Think of a post office. The counter clerk is the API. The ledger book is the database and audit log. The sorting room’s conveyor belt is the task queue. The mail carrier is the dispatcher. Your mailbox is the receiver. The clerk never walks letters to every house personally. The clerk drops them on the belt and carries on serving the next customer. That is why the dashboard feels fast even when a receiver is slow.
6How a Webhook Travels, Step by Step
Now we follow a single flag change on its journey, including what happens when the receiver is having a bad day.
sequenceDiagram
participant U as Engineer
participant F as Flagsmith API
participant Q as Task Queue
participant D as Dispatcher
participant R as Your Receiver
U->>F: Turn flag off in production
F->>F: Save new state and write audit entry
F->>Q: Enqueue webhook job
F-->>U: Change confirmed
Q->>D: Deliver job to worker
D->>R: POST message with signature
alt Receiver answers with success code
R-->>D: 200 OK
D->>D: Mark delivery complete
else Receiver fails or times out
R-->>D: Error or no reply
D->>Q: Schedule retry after a delay
Q->>D: Run retry later
D->>R: POST message again
end
A change is made
A person or script changes a feature in an environment. Flagsmith checks that the person is allowed to do it.
State and diary are saved
The new feature state goes into the database and an audit entry records who, what and when.
Jobs are queued
Flagsmith finds the webhooks that apply and places a delivery job for each on the background queue.
The person is told it worked
The dashboard confirms the change immediately. The person does not wait for webhooks to finish.
The message is built and sent
A worker builds the JSON message, adds a signature if a secret is set, and sends a POST request to your URL.
Your receiver replies
A success status code means the delivery is done. Anything else, or silence, may cause a retry.
Why the dashboard stays fast
The most important design choice in this journey is that delivery happens in the background. If Flagsmith waited for every receiver before telling you the change worked, one slow receiver could make the whole dashboard feel broken. Background delivery separates the speed of making a change from the speed of announcing it. The price of that separation is that announcements are not instant to the millisecond, and they can occasionally be delayed when the queue is busy.
A word on background workers
Background work needs something to do it. In the hosted Flagsmith service, the Flagsmith team runs that machinery for you. In a self-hosted installation, how background tasks run depends on how you deployed it. Some setups run tasks inside the main application process, while larger setups run a dedicated task processor so heavy background work never slows the web servers. We return to this in the chapter about self-hosting, because it changes how you think about reliability.
Because delivery is asynchronous, never build a workflow that assumes the webhook arrives before the person who made the change has finished their next click. Design receivers so that a slightly late message is harmless.
7Anatomy of a Flagsmith Webhook Message
A webhook is only as useful as the message inside it. Let us open the envelope and understand each piece.
The envelope and the letter
Every webhook has two parts. The first part is the set of headers, which are small labels attached to the request, such as the content type and, when you have configured a secret, a signature. The second part is the body, which is the actual letter. Flagsmith writes the body in JSON, so any programming language can read it. The exact fields can evolve between versions, so a good receiver reads the fields it needs and politely ignores the rest.
The event type
The body includes a name that says what kind of event this is. For the two families of webhooks, the main event names you will meet are a flag-updated event, a flag-deleted event and an audit-log-created event. Your receiver should look at this name first and decide what to do. A receiver that treats every message the same way is a receiver that will one day do something silly with a deletion.
The data inside
For environment webhooks, the data section describes the change in a before-and-after style. You can expect to find the following ideas, although the exact names and nesting are best confirmed against the current Flagsmith documentation for your version:
- Who made the change. A name or identifier of the user or key responsible.
- The new state. Whether the feature is enabled, what value it holds, which environment and feature it belongs to, and whether the change applies to a specific identity or to the general setting.
- The previous state. The same information as it was before the change, so you can see exactly what moved.
- A timestamp. When the change happened, which is vital for ordering messages correctly.
For organisation webhooks, the data section describes the audit log entry: a short human-readable description of what happened, who did it, when, and which object was touched.
The message is like a before-and-after photo from a home renovation. The new state is the finished room. The previous state is the room as it was. The timestamp is the date stamped on the corner of the photo. The change maker is the name of the builder written on the back. With all four, anyone can understand what happened without visiting the house.
Reading the message the safe way
Check the event type first
Route the message by its event name. Unknown names should be logged and ignored, never crash the receiver.
Read only what you need
Pull out the few fields your task requires. Extra or new fields will appear over time and should not break you.
Trust the timestamp, not arrival order
Messages can arrive out of order, so use the time inside the message when order matters.
Store the raw message
Keep the original bytes for a while. When something looks odd later, the raw record is your best evidence.
Flag values can contain information you may consider sensitive, such as configuration text. Remember that whatever is in the flag may travel in the message, so avoid placing secrets such as passwords inside flag values in the first place.
8Setting Up a Webhook, Step by Step
The setup is short, but each small choice affects security and reliability later. Here is the full journey from nothing to a working webhook.
Build or choose the receiver first
Before touching Flagsmith, have a web address ready that accepts POST requests, answers quickly and logs what it receives. A simple endpoint that only logs is a perfectly good start.
Open the right settings page
For an environment webhook, open the settings of that environment and find the webhooks area. For an organisation webhook, open the organisation settings and look for its webhooks area.
Create the webhook and enter the URL
Give it the full web address of your receiver. Always use a secure address that begins with https so the message is encrypted on its way.
Set a secret
Choose a long random secret and store a copy in your receiver’s secure configuration. Flagsmith uses it to sign each message so your receiver can prove the message is genuine.
Make sure it is enabled
Webhooks can be switched on and off. A disabled webhook sends nothing, which is a common reason for silence.
Test in a safe environment
Change a harmless flag in a non-production environment and confirm the message arrives, is verified and is stored. Only then repeat the setup for production.
Choosing the receiver address wisely
The address you give Flagsmith becomes a permanent doorway into your systems. Treat it with care. Use a dedicated path just for Flagsmith rather than a general-purpose address. Avoid putting secret tokens in the web address itself, because addresses tend to leak into logs. Use the signature instead of obscurity to prove who is calling.
One webhook or many?
You can create more than one webhook on the same environment, each pointing at a different receiver. This is useful when different teams care about the same events. A cache service, a chat bot and a compliance archive can each have their own address. The alternative is a single receiver that fans out to several downstream tools. Separate webhooks keep failures isolated, because a broken chat bot will not delay the cache refresh. A single fan-out receiver keeps configuration simpler and centralises security checks. Both patterns are valid, and we compare them in the chapter on design patterns.
Setting up a webhook is like setting up mail forwarding when you move house. You must first have the new address ready, then tell the post office, then prove it is really you by showing identification, which is the secret. And you should send a test letter to yourself before trusting the system with anything important.
Name your receivers after their purpose, such as the production cache refresher. In a year, nobody will remember what a generic name like test-hook-2 was for.
9Securing Your Webhooks
A webhook receiver is a public door. Anyone on the internet can knock on it. Security is how you make sure only the real Flagsmith gets in.
The threats in simple terms
If your receiver trusts every message it receives, a stranger can send a fake message claiming that a flag changed. If the receiver reacts by clearing caches, deploying code or paging people, the stranger has just gained a remote control. Three threats matter most: forgery, where someone fakes a message; tampering, where someone changes a real message on the way; and replay, where someone records a real message and sends it again later.
Encryption in transit
Always use https for your receiver address. Encryption keeps eavesdroppers from reading the message and prevents casual tampering along the route. It protects the content of the flag change from anyone who can see network traffic between Flagsmith and you.
Signatures: proving the message is genuine
When you configure a secret on a webhook, Flagsmith uses it to compute a signature from the exact bytes of the message body and sends that signature in a header. The signature is produced with a method called HMAC, which combines a message and a secret key using a hash function, in this case SHA-256, into a short fingerprint. Only someone who knows the secret can produce the right fingerprint for a given message. Flagsmith documents the header name and the exact method, and you should confirm both for your version, since your receiver must match them precisely.
Your receiver repeats the same calculation using its own copy of the secret and compares the result with the header. If they match, the message is genuine and unchanged. If they do not match, the receiver rejects the message with an error code and does nothing else. Two details matter a great deal. First, calculate the signature over the raw, unmodified bytes you received, not over a re-formatted version, because even a tiny change such as extra spaces produces a different fingerprint. Second, compare fingerprints using a constant-time comparison function so that attackers cannot learn the answer from tiny timing differences.
A signature is like the wax seal on a royal letter. Anyone can write a letter that says “from the king,” but only the king owns the seal stamp. When the letter arrives, you check the seal. If the seal is broken or wrong, you refuse the letter. The secret is the stamp. It must never be shared, and it must be kept somewhere safe.
Replay protection
A signature proves a message is real, but it does not prove the message is fresh. An attacker who records a genuine message could send it again tomorrow. To defend against this, receivers can check the timestamp inside the message and reject anything that is too old, and they can remember identifiers of messages they have already processed so that repeats are ignored. Treat replay protection as an extra layer, particularly for receivers that trigger powerful actions.
Protecting the secret
Do
- Generate the secret with a secure random generator and make it long.
- Keep it in a proper secrets manager, not in source code or a shared document.
- Use a different secret for each webhook and each environment.
- Rotate the secret on a schedule and immediately after any suspected leak.
Do not
- Paste the secret into chat messages or tickets.
- Reuse the staging secret in production.
- Log the secret or the full signature header in plain text.
- Leave the secret empty because the receiver is “only internal.”
Network-level defences
Beyond signatures, you can limit who can reach the receiver at all. A web application firewall can block obviously malicious traffic. If Flagsmith publishes the network addresses it sends from, you can restrict the receiver to accept connections only from those addresses. For self-hosted setups the sender is your own server, so private networking can keep the receiver off the public internet entirely. Remember that address lists change, so combine network rules with signatures, never replace signatures with them.
Least privilege inside the receiver
Give the receiver only the permissions it needs. A receiver that posts to a chat channel should not have the power to deploy code. A receiver that refreshes a cache should not have access to the customer database. If a forged or buggy message ever slips through, least privilege limits the damage to something small and fixable.
Webhook receivers that call other web addresses based on the content of a message can be tricked into reaching internal systems. Never use a value from the message as a web address to fetch. Treat all message content as data, never as instructions.
10Delivery Guarantees, Retries and Ordering
The internet is unreliable. Servers restart, networks hiccup and receivers get overloaded. This chapter explains what to expect when things go wrong, and how to design for it.
What does delivered even mean?
From the sender’s point of view, a delivery is successful when the receiver answers with a success status code in the two-hundreds range within the allowed time. Anything else, including an error code, a timeout or a refused connection, counts as a failure. The sender cannot see inside your receiver, so a success code is a promise from you that you have safely taken responsibility for the message.
Retries
When a delivery fails, Flagsmith does not give up immediately. It retries a limited number of times, waiting longer between attempts, a technique known as backoff. Backoff prevents a struggling receiver from being flooded by constant retries at the exact moment it needs room to recover. In self-hosted installations, the number of retries and the waiting pattern are typically configurable through settings, and the exact defaults are worth confirming in the current documentation. Importantly, retries are limited. After the final attempt fails, the message is not delivered, and you should plan for that.
At least once, and the duplicate problem
Systems that retry offer what is called at-least-once delivery. The message will arrive one or more times, but not necessarily exactly once. Consider a case where your receiver processes a message successfully but the success reply is lost on the way back. The sender sees a timeout, assumes failure and sends the message again. Your receiver now sees the same message twice. This is not a bug. It is a natural result of unreliable networks, and your receiver must be ready for it.
Imagine ordering a pizza by phone. If the call drops right after you say “yes, please deliver,” you do not know whether the order went through. A careful restaurant lets you call back and say “I think I already ordered,” and checks its records so you do not receive two pizzas. Idempotency, the ability to handle a repeat safely, is that check.
Idempotency: the golden rule
An operation is idempotent when doing it twice has the same result as doing it once. Setting a cache entry to a value is idempotent. Adding one to a counter is not. Design your receiver so that repeated messages are harmless. Two common techniques are available. The first is to remember identifiers or fingerprints of messages already processed and skip repeats. The second is to make the action itself naturally repeatable, for instance by always writing the full new state rather than applying a delta.
Ordering
If a person flips a flag on and then off a few seconds later, two messages are produced. They may not arrive in that order. A retry of the first message might land after the second message was delivered, leaving your system believing the flag is on when it is actually off. To defend against this, compare the timestamp inside each message with the timestamp of the last message you processed for the same feature and environment, and ignore anything older.
| Problem | Why it happens | Defence |
|---|---|---|
| Duplicate messages | Lost success replies cause retries | Idempotent actions and processed-message memory |
| Out-of-order messages | Retries and parallel workers | Compare timestamps and keep only the newest |
| Missing messages | Receiver down longer than the retry window | Periodic reconciliation using the Flagsmith API |
| Delayed messages | Busy queue or slow receiver | Do not require instant delivery for correctness |
| Bursts of messages | Bulk changes by automation | Queue on the receiver side and process steadily |
Reconciliation: the safety net
Because messages can be lost, mature teams treat webhooks as a fast signal and not as the only source of truth. They add a slow background check, perhaps every few minutes or hours, that asks the Flagsmith API for the real current state and fixes any difference. Webhooks give speed. Reconciliation gives certainty. Together they give both.
11Building a Reliable Receiver
The receiver is where most webhook problems are born. A small amount of structure turns a fragile endpoint into a dependable one.
flowchart TD
A["Incoming POST request"] --> B{"Signature valid?"}
B -- No --> C["Reject with client error and log attempt"]
B -- Yes --> D{"Message already seen?"}
D -- Yes --> E["Reply success and skip work"]
D -- No --> F["Save raw message to durable queue"]
F --> G["Reply success immediately"]
G --> H["Worker reads from queue"]
H --> I{"Event type known?"}
I -- No --> J["Log and discard safely"]
I -- Yes --> K["Apply action such as cache refresh or alert"]
K --> L{"Action succeeded?"}
L -- Yes --> M["Mark message complete"]
L -- No --> N["Retry later, then move to dead letter store"]
The principle: acknowledge fast, work later
The most valuable habit is to answer the sender quickly. A receiver should verify the message, save it somewhere durable, and reply with a success code within a moment. The real work, such as calling other services or updating big data stores, happens afterwards in a separate background worker. This protects you in two ways. The sender never times out because your work was slow, and a failure in your downstream tools does not make the sender think the delivery failed.
Walking through the flow
The diagram starts when a request arrives. The first gate is the signature check. A bad signature is rejected right away and logged, because repeated bad signatures may signal an attack. The second gate is the duplicate check. If the receiver has already handled this message, it simply replies with success and does nothing more, which is what makes retries harmless.
A fresh message is written to a durable queue, which is a waiting line that survives restarts. Only after the message is safely stored does the receiver reply with success. A worker then reads from the queue, checks whether it understands the event type, and carries out the action. If the action fails, the worker tries again later. After too many failures, the message is parked in a dead letter store, a special holding area where humans can look at problem messages without blocking everything else.
Think of a hotel front desk. When a courier arrives with a parcel, the desk clerk checks the courier’s identity, signs for the parcel, drops it into the mail room and lets the courier go. Delivering the parcel to the guest’s room happens later, by a different staff member. If the guest is out, the parcel waits. If it cannot be delivered for days, it goes to a lost-and-found shelf. The courier is never kept waiting for the room delivery.
Choosing a durable queue
Many technologies can act as the durable queue: a managed cloud queue service, a message broker, or even a database table used as a to-do list. The choice matters less than the properties: messages must survive restarts, workers must be able to retry, and you must be able to see how many messages are waiting. Start with whatever your team already operates well.
Keeping the receiver healthy
Reply in well under a second
Avoid slow work in the request path. Fast replies keep both sides happy.
Limit the body size
Reject enormous requests early so that a flood of junk cannot exhaust memory.
Run more than one copy
Place several receivers behind a load balancer so that one failure does not silence the whole path.
Return correct status codes
Use client error codes for bad requests and server error codes only for genuine temporary trouble, so retries happen only when they help.
12Real-World Use Cases
Webhooks become exciting when they connect flag changes to real outcomes. Here are practical patterns that teams use every day.
Instant chat alerts for risky changes
A receiver listens to the production environment and posts a short message into a team chat channel whenever a flag changes. The message names the flag, the person who changed it and the old and new states. Everyone sees risky changes as they happen, and the channel becomes a living change log. This is a favourite first project because it is simple and useful on day one.
Cache invalidation and refresh
Applications often cache flag results to stay fast. A webhook tells a small service to clear or refresh the relevant cache entries the moment a flag changes, which shortens the time during which some servers show old behaviour. Think of a large streaming service rolling out a new homepage: when product managers widen the rollout, caches across thousands of servers must learn about it quickly to keep every viewer’s experience consistent.
Compliance and audit archives
Regulated industries such as banking and healthcare must keep tamper-evident records of who changed what in production. An organisation webhook feeds every audit entry into a write-once archive, so records outlive the flag tool and can be shown to auditors. Because the entries come from Flagsmith’s own diary, the record is hard to fake.
Triggering pipelines and checks
Some flags control things that need follow-up work. When a flag that enables a new data format is switched on, a webhook can start a pipeline that warms up new indexes, or run a smoke test against production and report the result in chat. Automation reacts to people instead of waiting for someone to remember.
Analytics annotations
Data teams love timelines. A receiver writes each flag change into an analytics tool as an annotation. When an error rate or sales curve bends, analysts can see which flag changed at that moment. This turns mysterious graphs into explained ones.
Incident response and kill switches
During an incident, the first question is always, “What changed?” A webhook that streams every production flag change into the incident tool answers that question instantly. If the cause is a recent flag, responders know which switch to flip back. Some teams also page the owner of a flag when it changes outside business hours.
Keeping environments in sync
Some teams want a change in staging to be proposed automatically for production, or want a backup copy of production flags in another system. A receiver can copy changes, or open a review request, using the Flagsmith API. Because webhooks can arrive late or twice, such sync jobs should always use the idempotent, full-state approach described earlier.
Start with one low-risk use case, such as chat alerts. Once you trust the pipeline, build up to cache invalidation and automation. Each new use case reuses the same secure, reliable receiver you already built.
13Webhooks Compared with Other Options
Webhooks are one tool among several. Knowing the alternatives helps you choose the simplest tool that does the job.
The options on the table
Flagsmith offers several ways to keep other systems informed or in sync. Each has a different personality.
Webhooks
General-purpose messages sent to any address you control. Flexible, but you build and run the receiver.
Built-in integrations
Pre-built connections to popular tools for chat, monitoring and analytics. Little to build, but limited to what each integration offers.
Admin API polling
Your code asks Flagsmith for the current state on a timer. Simple and reliable, but slower and wasteful.
Audit log reads
Read the audit trail on demand for reports and reviews. Great for after-the-fact analysis.
SDK flag fetching
The way applications themselves read flag values, either by asking per request, polling, or evaluating locally. Not meant for informing other tools.
Real-time flag updates
Some plans can push flag changes directly to client applications. This is about applications, not about your operations tools.
flowchart TD
A["I need to react to flag changes"] --> B{"Is the reader my application code?"}
B -- Yes --> C["Use a Flagsmith SDK"]
B -- No --> D{"Does a built-in integration cover my tool?"}
D -- Yes --> E["Use the integration"]
D -- No --> F{"Do I need near real-time reaction?"}
F -- Yes --> G["Use a webhook with reconciliation"]
F -- No --> H["Poll the Admin API or read the audit log on a schedule"]
Reading the decision path
The first question separates application code from everything else. Your application should always read flag values through an SDK, because SDKs handle caching, targeting and performance for you. If the reader is not an application, check whether a built-in integration already speaks to your tool, because the least code is the best code. If neither applies and you need a fast reaction, a webhook is the answer, ideally paired with the safety net of periodic reconciliation. If speed does not matter, a scheduled read of the API or audit log is the calmest and simplest choice.
Choosing between these options is like choosing how to follow a favourite shop’s sales. You could visit the shop every day, which is polling. You could subscribe to its text alerts, which is a webhook. You could join a loyalty app that the shop already built, which is an integration. You could read the shop’s yearly report, which is the audit log. The best choice depends on how quickly you need to know and how much effort you want to spend.
Available integrations, plan limits and real-time features change over time and differ between plans. Always check the current Flagsmith documentation and your own plan before building a design around a specific capability.
14Hosted Versus Self-Hosted Considerations
Where Flagsmith runs changes who is responsible for what. Webhooks feel a little different depending on your choice.
With the hosted service
When you use the hosted Flagsmith service, the sender lives on the public internet and is operated by the Flagsmith team. Your receiver therefore needs to be reachable from the internet. That means a public address, a valid certificate for https, and protection against abuse. You do not need to worry about the machinery that queues and retries messages, because that belongs to the provider, but you should read the documentation about delivery behaviour so your expectations match reality.
With a self-hosted installation
When you run Flagsmith yourself, the sender is your own system, so you control more of the journey. You can keep the receiver on a private network, reach it through internal addresses, and use your own certificates. In return, you own the reliability of the background machinery. Webhook delivery needs working background task processing. If background tasks are processed inside the main application, heavy bursts of webhook work can compete with web traffic. In larger setups, teams run a dedicated task processor so webhook delivery, audit processing and other background duties are separated from the web servers.
Hosted advantages
- No machinery to operate for queues and workers.
- Updates and fixes are applied by the provider.
- Quick to start with a small team.
Hosted trade-offs
- Receivers must be reachable from outside your network.
- Less control over delivery tuning.
- Data policies may require review for strict industries.
Self-hosted advantages
- Receivers can stay on private networks.
- Delivery settings, such as retry behaviour, can be tuned.
- Full control over data location and access.
Self-hosted trade-offs
- You must keep workers, queues and databases healthy.
- You must plan upgrades and monitor background processing.
- Outages in your own platform also silence webhooks.
Network paths and outbound rules
On a self-hosted installation, the Flagsmith server must be allowed to make outbound web requests to your receiver. Strict firewalls and outbound proxies are a classic reason for webhook silence. Check that the worker process, not just the web process, has the right network permissions, since the worker is the one that sends the message.
Using the hosted service is like taking a taxi: someone else maintains the car, but you must tell the driver exactly where to drop you off, and the address must be reachable. Self-hosting is like owning the car: you decide the route and can drive down private roads, but you also pay for fuel, tyres and repairs.
15Monitoring, Logging and Metrics
You cannot fix what you cannot see. A webhook pipeline that nobody watches will eventually fail without anyone noticing.
Why silence is the scariest failure
When a web page crashes, people complain. When a webhook pipeline stops, nothing happens, and nothing happening feels like peace. A cache stays stale, an audit archive misses a week and nobody realises until the day it matters. Monitoring turns silent failure into loud alerts.
What to measure on the receiver
| Metric | What it tells you | Typical alert idea |
|---|---|---|
| Messages received per minute | Whether the pipeline is alive | Alert if zero during a period when changes are normally expected |
| Signature failures | Misconfigured secrets or attack attempts | Alert on a sudden rise |
| Reply time | Whether the receiver is fast enough | Alert if the slow tail grows toward the sender’s time limit |
| Error replies | Bugs or overload | Alert when the share of errors passes a small threshold |
| Queue depth | Whether workers keep up | Alert if messages keep piling up |
| Age of the oldest queued message | How late your reactions are | Alert if it passes your tolerance |
| Dead letter count | Messages that could not be processed | Alert on any growth and review daily |
| Duplicates skipped | How often retries happen | Watch for trends that hint at slow replies |
Logging that actually helps
Write one structured log line per message that includes the event type, the feature and environment names, the message timestamp, the decision taken, and a short identifier that links the entry to the stored raw message. Avoid logging secrets and avoid logging full flag values if they might be sensitive. When someone asks, “Did the cache hear about the 3 p.m. change?” you should be able to answer in a minute.
The sender’s side
Also look at what Flagsmith itself tells you. Review recent deliveries and failures wherever the product exposes them for your plan or deployment, and on a self-hosted system watch the health of the background task machinery, including backlog size and error rates. A rise in failed deliveries on the sender side that is not visible on the receiver side often points to network, certificate or firewall problems that stop requests from ever arriving.
Heartbeat testing
A clever safeguard is the heartbeat. Create a harmless flag in a quiet environment and flip it automatically on a schedule, for example once an hour. Your monitoring then expects a message at that rhythm. If the heartbeat message does not appear, you know the whole chain, from the sender through the network to your receiver, is broken, even when no human has changed a real flag.
A heartbeat monitor in a hospital does not wait for the patient to complain. It watches a steady rhythm and sounds an alarm when the rhythm stops. A scheduled harmless flag change is the pulse of your webhook pipeline.
Alert on the absence of expected messages, not only on the presence of errors. The most dangerous failures make no noise at all.
16A Troubleshooting Playbook
When a webhook does not arrive, follow the path of the message from the beginning to the end. Most problems fall into a few familiar groups.
Was a change really made?
Check that the change happened in the environment where the webhook is configured. A change in staging will not trigger a production webhook, and an organisation webhook only reflects audit entries, not every possible event.
Is the webhook enabled and correct?
Confirm it is switched on, and carefully compare the web address for typos, wrong paths or missing https.
Can the sender reach the receiver?
Check certificates, domain names, firewalls, proxies and any rule that blocks outbound requests. Certificates that have expired or lack the full chain are a very common cause.
Did the receiver get it and say no?
Look at the receiver’s access logs. A request that arrived and received an error code points to your code, your signature check or your size limits.
Is the background machinery healthy?
On a self-hosted system, confirm workers are running and the queue is draining. A stopped worker means no webhooks, however perfect the settings are.
Is it just late?
Check queue age and delivery timestamps. Sometimes the message is simply waiting behind a burst of other work.
Common symptoms and likely causes
| Symptom | Likely cause | First thing to try |
|---|---|---|
| Nothing ever arrives | Webhook disabled, wrong address or blocked network path | Re-check settings and send a test change to a request-inspection service |
| Messages arrive but are rejected | Secret mismatch or signature computed over altered bytes | Compare secrets and calculate over the raw body |
| Same message appears twice | Slow success reply caused a retry | Add duplicate handling and speed up the reply |
| Messages arrive in strange order | Retries and parallel processing | Compare timestamps before applying changes |
| Works in staging, not in production | Different secret, firewall or certificate | Compare configuration side by side |
| Sudden silence after a long period of success | Expired certificate or rotated secret | Check certificate dates and secret versions |
| Dashboard feels slow after a big change | Heavy background work competing with web traffic | Review worker capacity on a self-hosted system |
A safe way to look at real messages
While debugging, point a temporary webhook at a trusted request-inspection tool that simply shows incoming requests. You will see the headers and the body exactly as Flagsmith sends them. Use a non-production environment and harmless flags so that no sensitive configuration ends up in a third-party tool. Remove the temporary webhook when you are finished.
Troubleshooting a webhook is like tracing a missing parcel. First confirm it was really shipped, then check the label address, then check whether the courier could reach the street, then ask whether the neighbour signed for it and lost it, and finally ask whether the sorting centre is simply behind. You move along the route until you find where the parcel stopped.
17Design Patterns and Anti-Patterns
Teams that run webhooks for years tend to settle on the same few good habits, and fall into the same few traps.
Patterns that work
Ingest and process
One thin endpoint verifies and stores messages, and separate workers do the real work. This is the backbone of every reliable receiver.
Fan-out hub
One trusted receiver copies each verified message to many internal consumers, so each team subscribes internally without needing its own public endpoint.
Reconcile after signal
Use the webhook as a nudge, then call the Flagsmith API to fetch the real current state before acting. This avoids trusting stale or reordered content.
Dead letter review
Park failed messages in a holding area and review them on a schedule instead of letting them vanish.
Per-environment receivers
Give production and staging separate addresses and secrets so a mistake in one can never spill into the other.
Heartbeat flag
A scheduled harmless change proves the whole chain still works, even in quiet periods.
Single hub versus separate receivers
One fan-out hub
- Security checks live in one place.
- Fewer public doors to defend.
- Consumers can come and go without touching Flagsmith settings.
Hub trade-offs
- The hub becomes a critical shared service that needs strong uptime.
- A bad release of the hub can silence everyone at once.
- Ownership can become unclear between teams.
Anti-patterns to avoid
What it looks like
The receiver does all its work, including slow calls to other services, before it replies to the sender.
Why it hurts
Slow work causes timeouts, the sender retries, duplicates multiply, and one slow downstream tool can cascade into a flood of repeated messages.
Better approach
Verify, store durably, reply, and process in the background.
What it looks like
The receiver skips signature checks because it is “internal” or because the secret was awkward to set up.
Why it hurts
Anyone who discovers the address can forge changes and trigger real actions such as cache wipes or deploys.
Better approach
Always set a secret, always verify, and store the secret in a proper secrets manager.
What it looks like
The receiver treats the webhook as the only source of truth and never double-checks reality.
Why it hurts
One lost or reordered message leaves a system wrong forever, and nobody notices.
Better approach
Add periodic reconciliation against the Flagsmith API, and compare timestamps before applying changes.
What it looks like
One shared secret and one shared address are used for every environment and every team.
Why it hurts
A leak in a low-risk environment compromises everything, and a bug in a test receiver can disturb production.
Better approach
Use separate addresses and secrets per environment, and rotate them on a schedule.
18Best Practices and Common Mistakes
This chapter gathers the most valuable habits in one checklist, and the mistakes that most often cause pain.
Best practices
- Use https and a long random secret for every webhook.
- Verify signatures over the raw body with a constant-time comparison.
- Reply fast, then work in the background.
- Design every action to be safe when repeated.
- Compare message timestamps to ignore stale updates.
- Store raw messages for a period so you can investigate later.
- Reconcile periodically using the Flagsmith API.
- Monitor message volume, errors, queue age and dead letters.
- Test every new receiver in a non-production environment first.
- Write down who owns each webhook and what it does.
Common mistakes
- Forgetting that a webhook can be disabled, and wondering why nothing arrives.
- Calculating the signature over re-formatted content instead of the raw body.
- Replying with success before the message is safely stored.
- Replying with a server error for harmless bad input, which triggers pointless retries.
- Letting certificates expire without a reminder.
- Putting sensitive values inside flags, which then travel in messages.
- Assuming messages arrive exactly once and in order.
- Never reviewing the dead letter store.
- Building automation that can deploy or delete with no extra check.
- Leaving old webhooks pointing at retired addresses.
Good hygiene over time
Webhook setups age. People leave, services move, addresses change, and certificates expire. Schedule a short review every quarter. List every webhook, confirm each still has an owner and a purpose, rotate secrets, delete the ones nobody uses and confirm your monitoring still fires. A webhook that points to a decommissioned server is not just useless, it can become a security risk if someone later takes over that address.
Respecting the human side
Automation that reacts to flag changes must still respect people. If a receiver posts to chat, keep messages short and clear. If it triggers a deployment, require approval for risky environments. If it pages someone at night, make sure the message explains what changed and how to undo it. The best webhook pipelines make people calmer and better informed, not more anxious.
Never wire a webhook directly to a destructive action without a safety check. If the message is forged, duplicated or delayed, a direct connection to deletion or deployment can turn a small mistake into an outage.
19Testing Webhooks Safely
A webhook you have never tested is a webhook you cannot trust. Testing is cheap when you do it in the right order.
Test in layers
Good testing starts small and grows. First, test the receiver on its own by sending it hand-made sample messages, including valid ones, ones with a wrong signature, ones with unknown event types and ones that are far too large. Second, test the connection by creating a webhook in a non-production environment and changing a harmless flag. Third, test failure by deliberately making the receiver slow or broken for a few minutes and watching what the sender does. Finally, test recovery by bringing the receiver back and checking that retries, duplicates and reconciliation behave the way you designed.
Receiver alone
Send sample messages by hand. Confirm valid ones are accepted and invalid ones are rejected.
Real connection
Change a harmless flag in a test environment and confirm the whole path works end to end.
Failure drills
Switch the receiver off briefly and watch retries, alerts and dead letters behave as planned.
Recovery drills
Restore the receiver and confirm duplicates are ignored and reconciliation fixes any gaps.
What to check in each test
- The message was verified using the correct secret.
- The receiver replied quickly with a success code.
- The raw message was stored and can be found again.
- Sending the same message twice produced only one real action.
- An older message arriving after a newer one did not undo the newer state.
- An unknown event type was logged and ignored without errors.
- Alerts fired when the heartbeat message was deliberately withheld.
Testing a webhook is like a fire drill. You do not wait for a real fire to find out whether the alarm rings, the doors open and people know where to go. You rehearse in calm conditions so that real emergencies are routine.
Keep a dedicated sandbox project in Flagsmith with a harmless flag used only for webhook tests. Your drills will never disturb real features, and everyone knows where to experiment.
20Advanced Topics for Production Teams
Once the basics are solid, a few deeper ideas separate a good webhook pipeline from a great one.
Rotating secrets without downtime
Secrets should change from time to time, but a careless change can break delivery. Because Flagsmith signs with the secret you configured, there is a moment between changing the secret in Flagsmith and changing it in your receiver when the two disagree. A safe approach is to teach the receiver to accept either of two secrets for a short window. First, add the new secret to the receiver alongside the old one. Second, change the secret in Flagsmith. Third, watch for messages that verify with the new secret. Finally, remove the old secret from the receiver. If your setup allows two webhooks pointing at the same receiver, you can also create a second webhook with the new secret, confirm it works and then delete the old one.
Handling bursts
Automation can change hundreds of flags in seconds, producing a burst of webhooks. A receiver that processes each message with heavy work will fall behind, and retries will pile on. The cure is the durable queue from earlier, combined with a worker pool sized for steady throughput. Workers pull at their own pace, so the queue absorbs the spike. Consider also collapsing work: if twenty changes to the same feature arrive within a second, only the newest matters, so a worker can skip the older ones.
A burst of messages is like a sudden rush of customers at a ticket counter. If the clerk tries to serve everyone instantly, chaos follows. A queue lets people wait in a line while the clerk serves one at a time. If five people in the line want the same thing, the clerk can answer them all together.
Concurrency and race conditions
When several workers process messages at once, two messages about the same feature may be handled at the same moment. Without care, the older one can finish last and overwrite the newer result. There are three common defences. You can process messages for the same feature and environment in order, by routing them to the same worker. You can use conditional updates that only apply a change when its timestamp is newer than what is stored. Or you can fetch the real current state from the API after each signal and write that, which makes order irrelevant.
Evolving message formats
Software changes. A new version of Flagsmith may add new fields or new event types. Receivers that insist on an exact shape break the first time something is added. Build tolerant readers: ignore fields you do not know, treat missing optional fields as normal, and send unknown event types to a log. Keep a library of recorded real messages and replay them in your automated tests before upgrading, so format surprises appear in a test, not in production.
Multi-region and high availability
If the receiver is important, run it in more than one place. Place copies in different zones behind a load balancer so that one failure does not stop reception. If you span regions, remember that the same message might be delivered to either region on a retry, which makes the duplicate protection store a shared concern. Use a shared fast store for processed-message memory, or accept that rare duplicates can reach both regions and keep actions idempotent so duplicates are harmless.
Governance and ownership
Every webhook should have a named owner, a documented purpose, a list of downstream systems it touches and a recovery plan. Keep that information in a simple register. When a person leaves, review the webhooks they owned. When an incident review asks, “Who gets notified when this flag changes?” the register answers in seconds.
Cost and noise control
Every message has a cost, in compute, in storage and in human attention. Filter early. If a chat room only needs production changes for a handful of important flags, drop everything else at the receiver. If an archive needs everything, keep it compact and use cheap long-term storage. Fewer, clearer messages beat a flood that people learn to ignore.
Filtering usually happens in your receiver, because it is the part you fully control. Check the current Flagsmith documentation for any options that narrow which events are sent, since capabilities can differ between versions and plans.
21Lessons from the Wider Webhook World
Flagsmith is one of many products that send webhooks. The industry has been refining these ideas for years, and their lessons apply directly to your Flagsmith receivers.
Stripe: sign, timestamp and retry for days
The payments company Stripe signs every webhook event and includes a timestamp inside the signed data, so receivers can reject messages that are too old. Stripe also retries failed deliveries over a long period with growing delays. The lesson for your Flagsmith receiver: treat signatures and freshness checks as normal parts of the job, and expect that a message might show up long after it was first sent.
GitHub: delivery identifiers and manual redelivery
GitHub sends a unique identifier with each delivery and signs the body with a secret. Its dashboard shows recent deliveries, and lets people redeliver a message by hand when something went wrong. The lesson: unique identifiers make duplicate handling easy, and a human-friendly way to replay messages turns outages into small chores instead of disasters. Build a replay tool for your own receiver’s stored messages.
Shopify: answer quickly, process later
Online store platform Shopify tells developers to reply to webhooks quickly and handle the real work afterwards, because slow replies are treated as failures and trigger retries. The lesson mirrors our central rule: acknowledge fast, work in the background.
Slack: signing secrets and short deadlines
The team chat product Slack requires apps to verify a signature and a timestamp on incoming requests, and expects a prompt reply before it considers the delivery failed. The lesson: a short deadline and a verified signature are normal and healthy. Plan your receiver to meet both without strain.
Large streaming and retail platforms: events as the nervous system
Big consumer platforms that run thousands of services rely on event streams so each service can react to changes elsewhere without constant questioning. Feature flag changes are one more kind of event in that nervous system. Teams that publish flag changes into their shared event backbone gain a common timeline that supports debugging, auditing and automation in one place. The lesson: your Flagsmith webhook receiver can be the doorway that turns flag changes into events your whole company can use.
The details of each company’s webhook system change over time. Treat these examples as illustrations of good practice, and check each product’s own documentation before relying on specific numbers.
22A Worked Example from Start to Finish
Ideas become clear when they are attached to a story. Let us follow an imaginary online bookshop as it adds webhooks to its Flagsmith setup.
The company and its problem
Imagine a growing online bookshop with a website, a mobile app and a warehouse system. The team uses Flagsmith to control new features such as a redesigned basket page, a faster search box and a gift-wrapping option. They have three environments: development, staging and production. Over the last quarter they met four recurring pains. Product managers do not know when a flag goes live. The search service caches flag answers and sometimes shows old behaviour for several minutes. The security team has no easy list of production changes. And the on-call engineer wastes time during incidents hunting for what changed recently.
The design they chose
The team decided on one environment webhook for production and one organisation webhook for the audit feed. Both point to a single fan-out hub owned by the platform team. The hub verifies signatures, stores each message in a durable queue and replies quickly. Three small consumers read from the queue: a chat notifier, a cache refresher and an archive writer. A fourth job, the reconciler, runs every fifteen minutes and compares the real Flagsmith state with the cache.
flowchart LR
A["Flagsmith Production Environment"] --> B["Environment Webhook"]
A --> C["Organisation Audit Webhook"]
B --> D["Fan-out Hub"]
C --> D
D --> E["Durable Queue"]
E --> F["Chat Notifier"]
E --> G["Cache Refresher"]
E --> H["Archive Writer"]
I["Reconciler every 15 minutes"] --> G
I --> J["Flagsmith Admin API"]
F --> K["Team Chat Channel"]
G --> L["Search Service Cache"]
H --> M["Write-once Audit Store"]
Reading the picture
On the left, the production environment produces two streams of news. The environment webhook reports feature state changes. The organisation webhook reports audit entries. Both streams enter the fan-out hub, which is the single public door. The hub puts everything on a durable queue, and the three consumers each take what they need. The chat notifier writes a friendly sentence into the team channel. The cache refresher clears the right entries in the search service. The archive writer copies the audit entries into a store that cannot be edited afterwards. Finally, the reconciler works on a timer. It asks the Flagsmith admin interface for the current state, compares it with what the cache believes, and repairs any difference. If a webhook is ever lost, the reconciler catches the gap within fifteen minutes.
The bookshop’s design is like a newspaper office. Reporters, who are the webhooks, call in breaking news. The front desk, which is the hub, writes each call on a numbered slip and drops it in a tray. The editors, who are the consumers, pick up slips and act on them: one prints a headline, one updates the website and one files the story in the archive. At the end of each day, a fact checker, the reconciler, compares the printed paper with the facts and corrects any mistakes.
A day in the life
Morning rollout
A product manager widens the redesigned basket page from ten percent of shoppers to twenty-five percent. Flagsmith saves the change and queues two webhook jobs.
The hub accepts the news
Both messages arrive at the hub. Signatures check out, the messages are stored and the hub replies with success in a few milliseconds.
The consumers react
The chat notifier tells the team channel about the new rollout. The cache refresher clears the stale entries. The archive writer saves the audit record.
Afternoon surprise
A network problem makes the hub unreachable for six minutes. Flagsmith retries a few times but then gives up on two messages.
The safety net works
At the next quarter-hour, the reconciler notices that the cache disagrees with Flagsmith, repairs it and posts a short note in the channel that two messages were recovered by reconciliation.
Evening review
The platform team looks at the dead letter store, finds it empty, and checks the dashboard showing normal message volume and reply times.
What the team learned
Reconciliation paid for itself
Without the fifteen-minute check, the lost messages would have left the search service wrong until the next change.
Chat alerts built trust
Seeing every production change in one channel made product managers, support and engineers feel connected to the flags.
One hub simplified security
Signature checks, size limits and logging lived in a single place, so reviews were short and clear.
Monitoring caught the outage
A heartbeat flag flipped hourly showed a gap in messages and raised an alert before any human noticed.
You do not need the full bookshop design on day one. Begin with the hub and the chat notifier, add the cache refresher next, and bring in the archive and the reconciler as your confidence grows.
23Runbooks and Incident Scenarios
When something goes wrong at three in the morning, nobody wants to invent a plan. A short runbook turns panic into a checklist. Here are four scenarios every webhook team should rehearse.
Scenario one: the receiver is down
The hub stops answering because of a bad release or a failed server. Flagsmith keeps retrying for a short while, then gives up on the messages it could not deliver. The first job is to restore the receiver, ideally by rolling back the latest change. Once the receiver is healthy, look at your own logs to find the time window when it was unreachable. Then run reconciliation immediately for that window instead of waiting for the next scheduled run, and read through the audit log in Flagsmith to confirm which changes happened during the gap. Finally, write down how long the outage lasted and whether alerts fired on time.
Scenario two: the secret may have leaked
Someone pasted the secret into a public chat, or a log file containing it was shared. Treat this as urgent but calm. Create a new secret and follow the safe rotation steps so that the receiver temporarily accepts both. Change the secret in Flagsmith, confirm that messages verify with the new one, and remove the old one. Review the receiver’s logs for unusual messages that were signed with the old secret during the exposure, and check what actions those messages could have triggered. Afterwards, find out how the secret escaped and fix that habit, whether it was a shared document, a screenshot or a careless log line.
Scenario three: a storm of messages
An automation script goes wrong and flips hundreds of flags back and forth. The hub receives a flood of messages, the queue grows and the consumers fall behind. Resist the urge to switch off the hub, because the messages are evidence. First stop the misbehaving script. Next, let the queue drain while workers collapse repeated changes to the same feature, since only the newest matters. Watch the queue depth and the age of the oldest message. If the chat notifier is spamming a channel, pause that single consumer rather than the whole pipeline. After the storm, run reconciliation to confirm that the final state everywhere matches Flagsmith.
Scenario four: an accidental deletion
Someone deletes a feature in production, and a flag-deleted message flows to downstream systems. Perhaps the cache refresher now removes the flag from the cache. The immediate task is to restore the feature in Flagsmith, which may involve recreating it with its previous settings using the audit log as a guide. Then check that downstream systems recovered. This scenario is a reminder of why receivers should never take destructive actions based only on a single message. A careful receiver treats a deletion as a request to re-check the real state first.
| Scenario | First action | Recovery action | Follow-up |
|---|---|---|---|
| Receiver down | Restore or roll back the receiver | Run reconciliation for the gap | Review alert timing and capacity |
| Secret leaked | Rotate with a two-secret window | Review logs for forged traffic | Fix the habit that caused the leak |
| Message storm | Stop the source of changes | Let the queue drain and collapse repeats | Add rate limits and review automation |
| Accidental deletion | Restore the feature in Flagsmith | Confirm downstream systems recovered | Tighten permissions and add safety checks |
Keeping the runbook alive
A runbook that nobody reads is as useless as no runbook at all. Keep it short, keep it where on-call engineers can find it quickly, and rehearse it in calm moments. After every real incident, update it with what you learned. Include contact details for the owners of each webhook, links to dashboards, the location of the stored raw messages and the steps for reconciliation. Assign someone to review it every quarter, together with the list of webhooks and secrets.
A runbook is like the laminated emergency card in an aeroplane seat pocket. Passengers hope never to need it, but when the moment arrives, the clear pictures and short steps matter more than any clever improvisation. The crew has rehearsed the drill many times, so the real event feels familiar.
Capacity planning in plain words
Capacity planning sounds grand but boils down to three questions. How many messages arrive on a normal day, and how many on the busiest day? How long does one message take to process? How long can you tolerate a backlog? Multiply the busiest rate by the processing time to see how many workers you need, and add a healthy margin. Then test with a burst larger than anything you have seen. Flag changes are usually modest in number, but automation, bulk imports and busy release days can create sudden peaks. Planning for the peak means normal days feel effortless.
Do not size your receiver for the average day only. Incidents arrive on the worst days, and those are the days when accurate webhooks matter most.
24Glossary of Terms
A quick reference for every important word used in this guide, explained in plain language so you can look things up without rereading whole chapters.
| Term | Plain meaning |
|---|---|
| Webhook | An automatic message that one system sends to a web address you choose whenever a chosen event happens, so you hear about changes without asking repeatedly. |
| Sender | The system that creates and sends the message. In this guide the sender is Flagsmith, either the hosted service or your own installation. |
| Receiver | The web address and program you operate that accepts webhook messages, checks them, stores them and replies with a status code. |
| Payload | The body of the message, written in JSON, that describes what changed, who changed it, the previous state, the new state and the time. |
| Event type | A short name inside the message that tells you what kind of event occurred, such as a flag update, a flag deletion or a new audit log entry. |
| Environment webhook | A webhook attached to one Flagsmith environment that reports changes to feature states inside that environment. |
| Organisation webhook | A webhook attached to the whole organisation that reports new entries in the audit log, covering a broader range of activity. |
| Audit log | A running diary kept by Flagsmith of who changed what and when, useful for accountability, compliance and incident review. |
| Secret | A long random value shared only between Flagsmith and your receiver, used to sign and verify messages so forged ones can be rejected. |
| Signature | A short fingerprint calculated from the message body and the secret. If the receiver calculates the same fingerprint, the message is genuine and unchanged. |
| HMAC | A standard method that combines a message and a secret key with a hash function to produce a signature that only a holder of the key can create. |
| Idempotency | The property that doing something twice has the same effect as doing it once, which makes repeated messages harmless. |
| At-least-once delivery | A promise that a message will arrive one or more times, never silently zero when retries are available, but sometimes more than once. |
| Retry | A repeated attempt to deliver a message after a failure, usually with growing waits between attempts. |
| Backoff | The practice of waiting longer after each failed attempt so that a struggling receiver is not overwhelmed. |
| Queue | A waiting line for jobs or messages that lets work happen in the background and absorbs sudden bursts. |
| Dead letter store | A holding area for messages that could not be processed after several tries, kept so humans can review them later. |
| Reconciliation | A periodic check that compares what your systems believe with the real state in Flagsmith and repairs any differences. |
| Replay attack | An attack in which someone records a genuine message and sends it again later, defended against by checking timestamps and remembering handled messages. |
| Fan-out hub | A single trusted receiver that verifies each message once and then distributes it to several internal consumers. |
| Heartbeat flag | A harmless flag changed on a schedule so that the arrival of its messages proves the whole delivery chain is working. |
| Task processor | The background worker machinery that runs jobs such as webhook delivery, important for reliability in self-hosted installations. |
| Remote configuration | The ability to store values in Flagsmith, such as text or numbers, and change application behaviour without deploying new code. |
| Segment | A saved group of users who share a trait, allowing a flag to behave differently for that group. |
| Identity override | A flag setting that applies to one specific user and takes precedence over the general setting for that user. |
Share this glossary with new teammates before they touch a webhook. Agreeing on words such as retry, duplicate and reconciliation prevents long misunderstandings during incidents.
25Frequently Asked Questions
Short answers to the questions that beginners ask most often.
26Summary and Key Takeaways
Everything in this guide comes down to a few ideas you can carry into your next project.
Webhooks turn Flagsmith from a quiet switchboard into a talkative member of your engineering team. When a flag changes, the right people and the right systems find out immediately. We started with the silent switch problem and ended with a design for receivers that are secure, dependable and easy to operate. The core story is simple: Flagsmith saves the change, queues a background job, builds and signs a message, and sends it to your address. Your receiver verifies it, stores it, replies quickly and then works at its own pace.
Key Takeaways
- Two families, two jobs. Environment webhooks report feature state changes in one environment, and organisation webhooks report audit log entries across the whole organisation.
- Push beats poll for speed. A webhook tells you about a change within moments and without wasted checks, while SDKs remain the right way for applications to read flag values.
- Always verify. Use https, set a long random secret, and check the signature over the raw body with a constant-time comparison before doing anything else.
- Acknowledge fast, work later. Verify, store durably, reply with success, and process in a background worker so slow tools never cause timeouts or retry storms.
- Expect repeats, delays and disorder. Delivery is at least once, so design idempotent actions, compare timestamps and add periodic reconciliation with the Flagsmith API as a safety net.
- Watch for silence. Monitor message volume, errors, queue age and dead letters, and use a scheduled heartbeat flag so a broken pipeline is noticed within minutes.
- Treat webhooks as living infrastructure. Give each one an owner, test it in layers, rotate secrets without downtime, and review the whole list every quarter.