Modern development teams frequently need to react to pull request changes as soon as they happen. A new pull request may require an automated review, a new commit may trigger additional validation, and a merged pull request may require deployment or cleanup activities.
One common approach is to build a background service that repeatedly calls the GitHub API to check whether anything has changed. Although this approach works, it introduces unnecessary API requests, additional infrastructure, and delays between an event occurring and the application detecting it.
GitHub webhooks provide a more efficient approach. Instead of repeatedly asking GitHub whether a pull request has changed, an application can receive an HTTP notification whenever a subscribed event occurs.
This article explains how to use GitHub webhook events as an event-driven notification mechanism, build a secure webhook receiver with ASP.NET Core, and process pull request changes without continuously polling GitHub APIs.
Why Polling Pull Requests Becomes a Problem
Consider an application that monitors pull requests across several repositories. It needs to know when a pull request is opened, updated, assigned to a reviewer, or merged.
A straightforward implementation might execute a background job every minute:
while (!cancellationToken.IsCancellationRequested)
{
var pullRequests = await githubClient
.GetPullRequestsAsync();
await ProcessChangesAsync(pullRequests);
await Task.Delay(
TimeSpan.FromMinutes(1),
cancellationToken);
}
This implementation repeatedly retrieves pull request information, even when no changes have occurred.
As the number of repositories increases, the application generates more API requests. It also needs to compare previously retrieved information with the latest response to identify changes.
Polling introduces several problems:
- Unnecessary API requests when repositories are inactive.
- Delays between a pull request change and application processing.
- Additional storage for maintaining previous pull request states.
- Increased complexity when monitoring many repositories.
- Greater exposure to GitHub API rate limits.
For example, if an application checks 100 repositories every minute, it may generate thousands of requests over a working day without receiving any meaningful changes.
Polling still has a place in periodic reconciliation and recovery processes. However, it should not be the default mechanism for detecting every pull request change.
Understanding GitHub Webhook Events
GitHub webhooks allow an application to subscribe to specific repository or organization events. When a subscribed event occurs, GitHub sends an HTTP POST request to the configured endpoint.
The request contains a JSON payload describing the event.
For pull request monitoring, the most important event is pull_request. It supports several activity types, including:
Action | When it occurs |
|---|
opened | A new pull request is created |
synchronize | New commits are pushed to the pull request |
reopened | A previously closed pull request is reopened |
closed | A pull request is closed or merged |
ready_for_review | A draft pull request becomes ready |
converted_to_draft | A pull request becomes a draft |
review_requested | A reviewer is requested |
labeled | A label is added |
unlabeled | A label is removed |
assigned | A user is assigned to the pull request |
An application can subscribe to only the events relevant to its workflow.
For example, a deployment management application might need opened, synchronize, and closed. A code review automation system might also need review_requested and ready_for_review.
GitHub webhooks are HTTP push notifications, not a persistent WebSocket connection or a general-purpose streaming connection. The event-driven approach comes from receiving notifications whenever GitHub generates subscribed events.
Designing an Event-Driven Pull Request Architecture
A production application should avoid performing every operation directly inside the webhook HTTP request.
Imagine a pull request receives a new commit. The application may need to validate the event, update an internal database, trigger a build, notify reviewers, and update a dashboard.
Performing all these operations before responding to GitHub can make the endpoint slow and unreliable.
A better architecture separates event reception from event processing.
GitHub Repository
|
| Pull Request Event
v
ASP.NET Core Webhook Endpoint
|
| Verify Signature
| Identify Event
| Check Delivery ID
v
Message Queue
|
v
Background Worker
|
+------> Update Pull Request State
|
+------> Trigger Validation
|
+------> Notify Reviewers
|
+------> Update Dashboard
The webhook endpoint receives the event, validates it, and places it in a queue. It then returns a successful HTTP response.
A background worker processes the event independently.
This design provides several advantages:
- GitHub receives a response without waiting for lengthy operations.
- Temporary processing failures do not block the webhook endpoint.
- Background workers can scale independently.
- Multiple consumers can process different event categories.
- Queue monitoring makes failures easier to investigate.
Azure Service Bus, RabbitMQ, Amazon SQS, and other messaging systems can be used depending on the application's infrastructure.
Configuring a GitHub Webhook
Before writing the ASP.NET Core receiver, configure a webhook in GitHub.
Open the repository settings and navigate to the Webhooks section. Add a webhook and provide the following details:
Setting | Configuration |
|---|
Payload URL | Public HTTPS address of the ASP.NET Core endpoint |
Content type | application/json |
Secret | A randomly generated secret value |
SSL verification | Enabled |
Events | Select individual events or pull request activity |
For this example, assume the endpoint is:
https://api.example.com/webhooks/github
Select the pull request event rather than subscribing to every repository event.
Store the webhook secret in a secure configuration provider. Do not place it directly in application source code or commit it to a repository.
Building a Secure ASP.NET Core Webhook Receiver
The first responsibility of the receiver is to verify that the incoming request is genuinely associated with the configured GitHub webhook.
GitHub provides the X-Hub-Signature-256 header. It contains an HMAC-SHA256 signature calculated using the webhook secret and the original request body.
The application must calculate the expected signature and compare it with the received signature.
The following example implements signature validation.
using System.Security.Cryptography;
using System.Text;
public static class GitHubSignatureValidator
{
public static bool IsValid(
byte[] payload,
string? signature,
string secret)
{
if (string.IsNullOrWhiteSpace(signature) ||
!signature.StartsWith(
"sha256=",
StringComparison.Ordinal))
{
return false;
}
try
{
var receivedSignature =
Convert.FromHexString(signature[7..]);
var secretBytes =
Encoding.UTF8.GetBytes(secret);
var expectedSignature =
HMACSHA256.HashData(
secretBytes,
payload);
return CryptographicOperations.FixedTimeEquals(
expectedSignature,
receivedSignature);
}
catch (FormatException)
{
return false;
}
}
}
The implementation uses the original request bytes instead of converting the JSON payload into an object and serializing it again.
This is important because changing whitespace, property ordering, or character encoding can change the calculated signature.
The comparison also uses FixedTimeEquals instead of a normal string comparison.
Receiving and Identifying Pull Request Events
After signature validation, the endpoint can inspect the GitHub event headers.
Two headers are particularly important:
X-GitHub-Event identifies the event category.X-GitHub-Delivery identifies the individual delivery.
The following ASP.NET Core endpoint demonstrates the basic receiving process.
using System.Text.Json;
app.MapPost("/webhooks/github", async (
HttpRequest request,
IConfiguration configuration,
IWebhookEventQueue eventQueue) =>
{
var secret = configuration[
"GitHub:WebhookSecret"];
if (string.IsNullOrWhiteSpace(secret))
{
return Results.Problem(
"Webhook configuration is missing.");
}
using var memoryStream = new MemoryStream();
await request.Body.CopyToAsync(memoryStream);
var payload = memoryStream.ToArray();
var signature = request.Headers[
"X-Hub-Signature-256"].ToString();
if (!GitHubSignatureValidator.IsValid(
payload,
signature,
secret))
{
return Results.Unauthorized();
}
var eventType = request.Headers[
"X-GitHub-Event"].ToString();
var deliveryId = request.Headers[
"X-GitHub-Delivery"].ToString();
if (string.IsNullOrWhiteSpace(eventType) ||
string.IsNullOrWhiteSpace(deliveryId))
{
return Results.BadRequest();
}
if (eventType != "pull_request")
{
return Results.Ok();
}
using var document =
JsonDocument.Parse(payload);
var action = document.RootElement
.GetProperty("action")
.GetString();
await eventQueue.EnqueueAsync(
new GitHubWebhookEvent(
deliveryId,
eventType,
action,
payload));
return Results.Accepted();
});
The IWebhookEventQueue represents an application-specific queue abstraction. Its implementation should persist the message reliably before the endpoint returns a successful response.
The example also assumes that an appropriate request body size limit is configured and that the endpoint is protected by HTTPS.
For production applications, validate the expected event types and payload structure before enqueueing. Avoid accepting unlimited request bodies.
Notice that the endpoint does not execute a build, send notifications, or call several external APIs. Those operations belong in the background processing layer.
Processing Pull Request Events in the Background
Once the event is placed in a queue, a background worker can process it.
The event action determines what the application should do.
For example:
public async Task ProcessAsync(
GitHubWebhookEvent webhookEvent,
CancellationToken cancellationToken)
{
if (webhookEvent.EventType != "pull_request")
{
return;
}
switch (webhookEvent.Action)
{
case "opened":
await CreatePullRequestRecordAsync(
webhookEvent,
cancellationToken);
break;
case "synchronize":
await TriggerValidationAsync(
webhookEvent,
cancellationToken);
break;
case "ready_for_review":
await NotifyReviewersAsync(
webhookEvent,
cancellationToken);
break;
case "closed":
await UpdatePullRequestStatusAsync(
webhookEvent,
cancellationToken);
break;
}
}
This example separates event reception from business operations.
A real implementation should deserialize the payload into suitable models and extract the repository, pull request number, head commit SHA, and other required information.
It should also account for actions that the application does not handle. GitHub can introduce additional actions over time, so unknown actions should be safely ignored or recorded rather than causing the entire processing pipeline to fail.
Handling Duplicate and Out-of-Order Events
Event-driven systems must account for duplicate messages and delivery order.
A webhook delivery might be manually redelivered after a failure. A queue consumer might also process a message more than once if it fails after completing an operation but before acknowledging the message.
Without protection, the application might trigger the same build twice or send duplicate notifications.
Use the X-GitHub-Delivery value as a unique delivery identifier.
A common implementation maintains a delivery table:
Field | Purpose |
|---|
DeliveryId | Unique GitHub delivery identifier |
EventType | Event category |
Action | Pull request activity |
ReceivedAt | Time the event was received |
ProcessingStatus | Pending, Processing, Completed, or Failed |
Before processing an event, check whether its delivery ID has already been completed.
For reliable processing, record the event and its processing state transactionally. If a worker fails, the message can be retried without repeating completed operations.
Another important consideration is event ordering. GitHub documents that webhook deliveries may arrive in a different order from the order in which the events occurred.
For example, a synchronize event might be processed after a later closed event.
To avoid restoring outdated information, compare event timestamps and commit SHAs where appropriate. For operations that require the current pull request state, retrieve the latest state from GitHub rather than assuming the incoming event represents the newest state.
Security Considerations for Pull Request Automation
Webhook signature validation confirms that the payload matches the configured secret. It does not mean that the code inside a pull request is safe to execute.
This distinction matters when an application builds code from external contributors.
A pull request from a fork may contain untrusted changes. Do not expose deployment credentials, repository write tokens, or other secrets to untrusted build scripts.
Use restricted permissions, isolated build environments, and short-lived credentials where possible.
Other important security practices include:
- Use HTTPS for the webhook endpoint.
- Store webhook secrets in a secure secret manager.
- Subscribe only to required events.
- Validate event types and payload fields.
- Apply request size limits.
- Avoid logging webhook secrets or sensitive payload information.
- Restrict access to queue messages and processing infrastructure.
- Monitor failed signature checks and unusual delivery patterns.
For applications that use GitHub Actions, carefully distinguish between pull_request and pull_request_target. The latter runs in the context of the base repository and can have access to elevated permissions. It must not be used to execute untrusted pull request code with privileged credentials.
Common Mistakes to Avoid
Mistake | Better approach |
|---|
Processing everything inside the webhook request | Enqueue events and process them asynchronously |
Comparing signatures using normal equality | Use constant-time comparison |
Parsing JSON before signature validation | Validate the original request body |
Subscribing to every GitHub event | Subscribe only to required events |
Assuming events arrive in order | Use timestamps and current repository state |
Processing the same delivery repeatedly | Implement delivery ID-based idempotency |
Assuming failed deliveries are automatically retried | Monitor failures and implement redelivery |
Trusting code from every pull request | Isolate builds and restrict credentials |
Monitoring and Troubleshooting Webhook Processing
A webhook architecture should provide visibility into both event reception and background processing.
At minimum, record the delivery ID, repository name, event type, action, received timestamp, processing status, and failure reason.
Avoid logging secrets or unnecessary sensitive information.
Useful monitoring metrics include:
- Total webhook deliveries received.
- Invalid signature count.
- Events successfully added to the queue.
- Queue processing latency.
- Failed or abandoned messages.
- Duplicate delivery count.
- Background worker failures.
GitHub also provides recent delivery information in the webhook configuration. Developers can inspect request headers, payloads, response codes, and delivery failures.
One important operational detail is that GitHub expects a successful 2xx response within 10 seconds. If the endpoint takes longer, GitHub can terminate the connection and mark the delivery as failed.
GitHub does not automatically redeliver failed webhook deliveries. Applications should monitor delivery failures and implement an appropriate manual or automated redelivery process.
Summary
GitHub webhooks provide an event-driven alternative to repeatedly polling pull request APIs. Instead of continuously checking repositories for changes, an application can subscribe to specific events and receive notifications when pull request activity occurs.
An ASP.NET Core webhook receiver can validate incoming requests using HMAC-SHA256, identify event types through request headers, and send valid events to a background processing queue.
For production systems, signature validation, delivery ID-based idempotency, asynchronous processing, event ordering, and secure handling of untrusted pull request code are essential.
The result is a more responsive and scalable integration that reduces unnecessary API requests while allowing applications to react to pull request changes as they happen.
Join the conversation! Your thoughts help the community grow.