MSBA-273 · Lesson 3 of 12 · 21 min
Webhooks and service endpoints
▶ Video coming soon A video version of this lesson is on the way.
The Web API answers when another system asks. Many integrations need the opposite: Dataverse should tell another system when something happens. The example Signe chose for the third session came from the campus security office, whose dispatch tool needed to know within a minute when a high-priority safety work order was created, so that an officer could be sent to secure the area while Facilities arranged the repair. Polling the Web API every minute from the dispatch tool would work, badly: thousands of empty queries a day, a delay of up to a minute, and a second copy of the filtering logic. The better answer was to let the Dataverse event pipeline push the event out. Wiremu prototyped two ways of doing that in his developer environment: a webhook and an Azure Service Bus endpoint.
Pushing events out of Dataverse
The event pipeline covered in the earlier courses runs registered steps when a message such as Create or Update is processed for a table. A step usually runs a plug-in. It can instead send the execution context to an external endpoint. Two kinds of endpoint are available. A webhook sends an HTTP POST to any web address the organization chooses. A service endpoint posts to Azure Service Bus or Azure Event Hubs, where the message waits in a queue or topic until a receiver reads it. Both are registered with the Plug-in Registration Tool, and both use the same step settings as plug-ins: the message, the table, the stage, synchronous or asynchronous mode, filtering attributes and images.
Power Automate offers a third route, the Dataverse trigger that starts a cloud flow when a row is added, modified or deleted, which suits low-code receivers. Lesson 9 looks at flows that call external APIs. This lesson concentrates on the two pro-code routes and on how to choose between them.
Registering a webhook
A webhook registration has two parts. First the developer registers the endpoint: a name, the HTTPS address of the receiver, and an authentication option. Then the developer registers one or more steps that use the endpoint, choosing the message, table, stage and mode exactly as for a plug-in step. Wiremu registered a step on Create of lcc_workorder, in the PostOperation stage, asynchronous, so that the dispatch tool would be told only after the work order had been saved.
Three authentication options control what Dataverse adds to each request. WebhookKey adds a key as a query string parameter, which matches the function key that Azure Functions expect. HttpHeader adds one or more named header values. HttpQueryString adds one or more named query string values. None of these is strong authentication: each is a shared value that the receiver compares with its own copy. The receiver must therefore require HTTPS, compare the value in constant time, keep the value in a secret store, and rotate it on a schedule. Header values are preferable to query strings because query strings are more likely to appear in web server logs.
| Setting | Wiremu's prototype |
|---|---|
| Endpoint name | Security dispatch webhook (Wiremu Dev) |
| Endpoint address | An HTTPS Azure Function in the test subscription |
| Authentication | HttpHeader, with a value held in Key Vault |
| Message and table | Create on lcc_workorder |
| Stage and mode | PostOperation, asynchronous |
| Filter | Receiver ignores work orders that are not priority 1 safety jobs |
| Images | Post-image with six columns only |
What the receiver gets
Dataverse sends the execution context as JSON in the body of a POST. The object is a RemoteExecutionContext, the serializable form of the context a plug-in receives: the message name, the primary table and row identifier, the user and the initiating user, the depth, the correlation identifier, the input and output parameters, and any images registered on the step. Several headers repeat key facts so that the receiver can route the request before parsing the body: x-ms-dynamics-organization names the environment, x-ms-dynamics-entity-name the table, x-ms-dynamics-request-name the message, and x-ms-correlation-request-id the correlation identifier.
POST https://lcc-dispatch-hook-test.azurewebsites.net/api/workorder-created
x-ms-dynamics-organization: lumenvale-dev-wiremu.crm3.dynamics.com
x-ms-dynamics-entity-name: lcc_workorder
x-ms-dynamics-request-name: Create
x-ms-correlation-request-id: 3d0e…
x-lcc-hook-key: <value compared by the receiver>
Content-Type: application/json
{
"MessageName": "Create",
"PrimaryEntityName": "lcc_workorder",
"PrimaryEntityId": "6f1c2b0e-…",
"Depth": 1,
"Stage": 40,
"InitiatingUserId": "…",
"PostEntityImages": [ { "key": "Post", "value": { "Attributes": [ … ] } } ],
…
}The payload is large and verbose, because it is the whole context. When the body would exceed 256 kilobytes, Dataverse adds the header x-ms-dynamics-msg-size-exceeded and removes the parent context, the input parameters and the images, leaving the receiver to read what it needs through the Web API. A receiver that depends on an image must handle that case. The better design is to keep the payload small in the first place: register images with only the columns the receiver uses, and use filtering attributes on Update steps so that irrelevant changes send nothing.
Worked problem
Keeping a payload under the size limit
The first draft of a webhook step on Update sent the context with full pre- and post-images. The context without images was about 40 kilobytes, and each full image held 120 columns averaging about 1.5 kilobytes of JSON. What was the payload size, and what happens with images limited to the eight columns the receiver uses?
Show solution
- Each full image is 120 times 1.5, which is 180 kilobytes; two images are 360 kilobytes.
- With the 40-kilobyte context the draft sends about 400 kilobytes, over the 256-kilobyte limit, so Dataverse strips the images and sets the size-exceeded header.
- Eight columns at about 1.5 kilobytes is 12 kilobytes per image, so the revised payload is about 40 plus 24, or 64 kilobytes, well under the limit.
Answer: About 400 kilobytes before, so the images would be removed; about 64 kilobytes after limiting the images to eight columns.
Timeouts, retries and synchronous webhooks
Dataverse waits 60 seconds for the receiver to respond. Only a 2xx status counts as success. For 502, 503 and 504 responses Dataverse retries once; other failures are not retried. What happens next depends on the step's mode.
An asynchronous step runs as a system job after the main operation has completed. If the webhook fails, the system job records the failure, and administrators can see it in the system jobs list. The work order is saved either way; the dispatch tool simply did not hear about it. An asynchronous step is the right default for notifications, because a slow or broken receiver cannot affect people using the app.
A synchronous step runs inside the operation. If the webhook fails or times out, the user sees an error saying the endpoint is unavailable, and the whole operation is rolled back: the work order is not saved. That can be useful when the external system must accept the change for it to be valid, for example a check that a supplier is approved in another system. It also carries a trap. The request has already reached the receiver before the rollback, and Dataverse cannot recall it. If the receiver acted on it, the two systems now disagree. Synchronous webhooks also put the receiver's response time inside the user's save, so a receiver that takes three seconds makes every save three seconds slower.
| Question | Asynchronous webhook | Synchronous webhook |
|---|---|---|
| When it runs | After the operation completes, as a system job | Inside the operation |
| If the receiver fails | The system job fails; the row is still saved | The operation is rolled back and the user sees an error |
| Effect on users | None | Adds the receiver's response time to every save |
| Risk | The external system may miss an event | The receiver may act on a change that was then rolled back |
| Good for | Notifications and downstream updates | Rare validations that must block the save |
Azure Service Bus endpoints
A service endpoint registration points to an Azure Service Bus namespace or an Event Hubs namespace. Dataverse supports several contracts: a queue, a topic, a one-way or two-way relay, a REST relay, and an event hub. Queues and topics are the common choices. With a queue, one receiver takes each message. With a topic, each subscription receives its own copy, so several systems can react independently to the same event. Authentication uses a shared access signature key or token for the namespace, configured in the registration.
Steps registered against a service endpoint are always asynchronous. Dataverse runs the post as a system job and places the execution context on the queue or topic in the format chosen in the registration: .NET binary, which is the default, XML or JSON. Choose JSON unless every receiver is a .NET program that understands the binary format. When the message would exceed 192 kilobytes, Dataverse removes the parent context, the input parameters and the images and adds a property saying the size was exceeded; if the message is still too large, it is not sent. If posting fails because of an error on the Azure side, the system job waits and retries with increasing intervals.
Service Bus changes the shape of the integration in a useful way. The receiver does not need to be online when the event happens. Messages wait in the queue until a receiver reads them, and the receiver can process them at its own pace. Service Bus also offers dead-letter queues for messages that cannot be processed, duplicate detection within a configured window, sessions for ordered processing, and scheduled delivery. For the security dispatch scenario, a queue meant that a maintenance window on the dispatch tool would delay notifications rather than lose them.
For cases where the default context is not the right message, a developer can write a custom Azure-aware plug-in. The plug-in builds its own message and posts it through the service endpoint notification service that Dataverse provides to plug-ins. Wiremu did not need that for the prototype, but noted it as the way to send a smaller, purpose-built message if the dispatch tool's vendor asked for one.
Event Grid and other Azure services
Dataverse service endpoints do not post to Azure Event Grid directly. Teams that want Event Grid's fan-out and filtering usually place a small Azure Function or a Service Bus subscription in between: Dataverse posts to Service Bus or a webhook, and the receiver publishes an event to Event Grid for other subscribers. Signe's advice was to add that layer only when there were several independent subscribers that needed it. For one or two receivers, a Service Bus topic already provides fan-out without another service to secure and monitor.
Designing a good receiver
Whichever endpoint is chosen, the receiver's design decides whether the integration is reliable. Wiremu's prototype receiver followed five rules. It authenticated every request, rejecting any without the expected header value or from an unexpected organization. It answered quickly, placing the work on its own queue and returning success within a second instead of doing slow work before responding. It was idempotent: delivery is at least once, so the same event could arrive twice, and the receiver used the work order's identifier and the correlation identifier to ignore duplicates. It logged the correlation identifier with every action so that a problem could be traced back to the Dataverse operation. And it never trusted the payload blindly: when it needed current data, it read the row through the Web API using its own application identity.
// C# Azure Function (isolated worker): accept the webhook, check the header, queue the work.
[Function("WorkOrderCreated")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
{
if (!req.Headers.TryGetValues("x-lcc-hook-key", out var keys) ||
!CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(keys.First()), _expectedKey))
return req.CreateResponse(HttpStatusCode.Unauthorized);
var body = await new StreamReader(req.Body).ReadToEndAsync();
var correlation = req.Headers.GetValues("x-ms-correlation-request-id").First();
await _queue.SendMessageAsync(new ServiceBusMessage(body) { MessageId = correlation });
return req.CreateResponse(HttpStatusCode.Accepted); // answer fast; work happens later
}Choosing between the options
| Need | Usual choice |
|---|---|
| One receiver with an HTTPS endpoint, simple notification | Asynchronous webhook |
| Receiver may be offline; events must not be lost | Service Bus queue |
| Several independent receivers of the same event | Service Bus topic with subscriptions |
| High-volume event stream for analytics | Event Hubs endpoint |
| Business users maintain the reaction | Cloud flow with the Dataverse trigger |
| External check that must block the save | Synchronous webhook, used sparingly |
Signe's recommendation for the dispatch scenario was a Service Bus queue rather than a webhook. The dispatch tool's vendor could read from a queue, the tool was patched monthly with an hour of downtime, and a queue would hold notifications through that window. The recommendation went into the design notes for the security office to consider; nothing was deployed beyond Wiremu's developer environment.
Common mistakes
MistakeRegistering a synchronous webhook for a simple notification.
InsteadUse asynchronous mode so the receiver cannot slow down or block saves.
MistakeDoing slow work in the receiver before responding.
InsteadAcknowledge within seconds and process from a queue, well inside the 60-second timeout.
MistakeAssuming each event arrives exactly once.
InsteadMake the receiver idempotent; deliveries are at least once.
MistakeRegistering full images on a webhook step.
InsteadInclude only the columns the receiver needs so the payload stays under the size limit.
MistakeTreating the webhook key as strong authentication and putting it in the query string.
InsteadPrefer a header value kept in Key Vault, require HTTPS and rotate the value.
MistakeExpecting Dataverse to post to Event Grid directly.
InsteadPost to Service Bus or a webhook and publish to Event Grid from the receiver if needed.
Summary and key terms
- Webhooks and service endpoints let registered pipeline steps push events out of Dataverse; both are registered with the Plug-in Registration Tool.
- Webhooks POST the execution context as JSON to an HTTPS address, authenticated with a key, header or query string value.
- Receivers have 60 seconds; only 2xx is success, and 502, 503 and 504 are retried once; synchronous failures roll back the operation.
- Service Bus endpoints are asynchronous, support queues, topics, relays and Event Hubs, and hold messages until receivers are ready.
- Payloads over 256 kilobytes for webhooks or 192 kilobytes for Service Bus lose their images and parameters; keep images small.
- Good receivers authenticate, respond quickly, are idempotent and log the correlation identifier.
- Webhook
- A registration that makes Dataverse send an HTTP POST with the execution context to an external address when a step runs.
- Service endpoint
- A registration that makes Dataverse post the execution context to Azure Service Bus or Event Hubs.
- RemoteExecutionContext
- The serializable form of the execution context that webhooks and service endpoints send.
- Dead-letter queue
- A Service Bus sub-queue that holds messages that could not be delivered or processed.
- Idempotent
- Able to receive the same request more than once with the same result as receiving it once.
- Correlation identifier
- An identifier shared by all operations caused by one original request, used to trace them.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why did Signe recommend a Service Bus queue for the security dispatch tool?
Show answer
The tool had monthly downtime; a queue holds messages until the receiver is ready, so notifications would be delayed rather than lost.
A synchronous webhook times out. What does the user see, and what is the risk?
Show answer
An endpoint-unavailable error and a rolled-back save; the receiver may already have acted on the request.
Which header tells a receiver that the payload was trimmed?
Show answer
x-ms-dynamics-msg-size-exceeded.
Name two ways a receiver can make itself idempotent.
Show answer
Track processed event or correlation identifiers and ignore repeats; use upserts keyed on the source row so repeats change nothing.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.