Applications that integrate with GitHub often need to react when something happens to a pull request.
For example, an internal development platform might need to start a validation workflow when a pull request is opened. A code review assistant might need to process new review comments. A deployment system might need to respond when a pull request is merged.
The straightforward approach is to keep asking GitHub whether something changed.
That is polling.
Application
|
| "Has the PR changed?"
v
GitHub API
|
| No
v
Wait
|
| "Has the PR changed?"
v
GitHub API
This approach is simple, but it creates unnecessary API requests, adds delay, and becomes harder to manage as the number of repositories and pull requests increases.
A better approach is event-driven integration.
Instead of repeatedly asking GitHub for changes, configure GitHub to notify your application when the required event occurs. Your application can then process the event and perform the appropriate action.
Pull Request Event
|
v
GitHub Webhook
|
v
Your API
|
v
Validate / Queue / Process
This article explains how to build that pattern with ASP.NET Core and GitHub webhooks while focusing on reliable production behavior.
Polling vs Event-Driven Processing
Polling means that your application periodically checks GitHub for changes.
For example:
while (!cancellationToken.IsCancellationRequested)
{
await CheckPullRequestsAsync(cancellationToken);
await Task.Delay(
TimeSpan.FromSeconds(30),
cancellationToken);
}
This works, but the application cannot know exactly when a change happens.
If the interval is 30 seconds, a new pull request may be detected almost immediately or nearly 30 seconds later.
Polling also creates requests when nothing has changed.
Webhooks reverse the responsibility.
GitHub sends an HTTP request to your application when an event occurs.
Area | Polling | Webhooks |
|---|
Detection | Application asks GitHub | GitHub sends event |
API requests | Repeated | Event-driven |
Reaction time | Depends on interval | Usually near event time |
Idle traffic | High | Low |
Implementation | Simple initially | Requires endpoint and security |
Reliability | Requires tracking state | Requires delivery handling |
Scaling | Can become expensive | Better suited to event-driven workloads |
For event-driven applications, webhooks are generally a better fit when the external platform already provides reliable event notifications.
What Is a GitHub Pull Request Webhook?
A GitHub webhook allows an application to receive HTTP notifications when selected repository events occur.
For pull request processing, the webhook can be configured for events such as:
opened
closed
reopened
synchronize
edited
labeled
unlabeled
The exact events you need depend on the application.
For example, if a code validation service needs to run whenever new commits are pushed to an existing pull request, the synchronize event is important.
If the application only needs to know when a pull request is created, opened may be sufficient.
This distinction matters because subscribing to unnecessary events increases processing work.
Designing the ASP.NET Core Webhook Endpoint
A webhook receiver should be small and focused.
A minimal ASP.NET Core endpoint can look like this:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/github/webhooks")]
public class GitHubWebhookController : ControllerBase
{
[HttpPost]
public IActionResult Receive()
{
var eventName = Request.Headers["X-GitHub-Event"].ToString();
return Ok(new
{
Event = eventName
});
}
}
The X-GitHub-Event header tells the application which GitHub event was delivered.
However, production webhook handling requires more than reading the event name.
The application should validate the request, identify the repository and event, process only supported events, and avoid doing long-running work directly inside the HTTP request.
Validate the Webhook Signature
A webhook endpoint is publicly reachable in most architectures.
That means anyone who knows the endpoint could potentially send a fake request.
GitHub supports webhook signatures that allow the receiving application to verify that a request was generated using the configured webhook secret.
A typical ASP.NET Core implementation can calculate the HMAC SHA-256 signature:
using System.Security.Cryptography;
using System.Text;
static bool IsValidSignature(
string payload,
string signature,
string secret)
{
var key = Encoding.UTF8.GetBytes(secret);
var body = Encoding.UTF8.GetBytes(payload);
using var hmac = new HMACSHA256(key);
var hash = hmac.ComputeHash(body);
var expected =
"sha256=" + Convert.ToHexString(hash).ToLowerInvariant();
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(expected),
Encoding.UTF8.GetBytes(signature));
}
The use of CryptographicOperations.FixedTimeEquals is important because signature comparison should not rely on a normal string comparison that can introduce timing-related weaknesses.
The webhook secret itself should not be stored directly in source code.
For ASP.NET Core, configuration can be used instead:
var webhookSecret =
configuration["GitHub:WebhookSecret"];
In production, the actual value should come from protected configuration or a managed secret store.
Read the Raw Request Body
Signature validation must be performed against the original request payload.
This is important because changing the body before calculating the signature can produce a different hash.
A simplified endpoint can read the raw body:
[HttpPost]
public async Task<IActionResult> Receive()
{
using var reader = new StreamReader(Request.Body);
var payload = await reader.ReadToEndAsync();
var signature =
Request.Headers["X-Hub-Signature-256"].ToString();
var eventName =
Request.Headers["X-GitHub-Event"].ToString();
// Validate signature before processing the payload.
return Ok();
}
The important sequence is:
Receive request
|
v
Read raw payload
|
v
Validate signature
|
v
Identify event
|
v
Queue work
|
v
Return response
Do not treat the event body as trusted input simply because it came from a webhook endpoint.
Deserialize the Pull Request Event
After the signature is validated, the application can deserialize the payload into a suitable model.
For example:
public sealed class PullRequestEvent
{
public string Action { get; set; } = string.Empty;
public RepositoryInfo Repository { get; set; } = new();
public PullRequestInfo PullRequest { get; set; } = new();
}
public sealed class RepositoryInfo
{
public string FullName { get; set; } = string.Empty;
}
public sealed class PullRequestInfo
{
public int Number { get; set; }
public string Title { get; set; } = string.Empty;
}
The actual event payload contains considerably more information, so production applications should model only the fields they need.
This keeps the application easier to maintain.
Do Not Perform Long-Running Work Inside the Webhook Request
This is one of the most important design considerations.
Suppose the application receives a pull request event and then starts:
Repository analysis
Static analysis
AI processing
Build execution
Test execution
Deployment validation
Doing all of that before returning the webhook response creates unnecessary risk.
A better design is to acknowledge the webhook quickly and move the actual work to a queue.
GitHub
|
v
Webhook API
|
| Validate
|
v
Queue
|
v
Background Worker
|
+--> Build
+--> Test
+--> Analyze
+--> Update status
The endpoint becomes responsible for receiving and validating the event.
The worker becomes responsible for processing it.
Use an Internal Queue
For smaller ASP.NET Core applications, a background queue can be implemented using Channel<T>.
using System.Threading.Channels;
public sealed class WebhookQueue
{
private readonly Channel<string> _channel =
Channel.CreateUnbounded<string>();
public ValueTask EnqueueAsync(
string payload,
CancellationToken cancellationToken)
{
return _channel.Writer.WriteAsync(
payload,
cancellationToken);
}
public IAsyncEnumerable<string> ReadAllAsync(
CancellationToken cancellationToken)
{
return _channel.Reader.ReadAllAsync(
cancellationToken);
}
}
A hosted service can consume the queue:
public sealed class WebhookWorker
: BackgroundService
{
private readonly WebhookQueue _queue;
public WebhookWorker(WebhookQueue queue)
{
_queue = queue;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
await foreach (var payload in
_queue.ReadAllAsync(stoppingToken))
{
await ProcessWebhookAsync(
payload,
stoppingToken);
}
}
private static Task ProcessWebhookAsync(
string payload,
CancellationToken cancellationToken)
{
// Perform longer-running processing here.
return Task.CompletedTask;
}
}
This pattern keeps the webhook endpoint responsive.
For larger systems, an external queue or message broker is usually more appropriate because it can provide persistence, retry handling, scaling, and better failure recovery.
Handle Duplicate Events
Webhook consumers should not assume that every event will be processed exactly once.
A delivery may be retried or processed more than once because of network failures, application restarts, or response problems.
The application should therefore make important operations idempotent.
For example, store a unique delivery identifier:
delivery-id
repository
event
received-at
processing-status
Before processing an event, check whether that delivery has already been handled.
Conceptually:
Receive event
|
v
Check delivery ID
|
+---- Already processed ---> Return
|
v
Store delivery
|
v
Queue processing
This prevents duplicate processing from triggering duplicate builds, notifications, or deployments.
Handle Pull Request Updates Correctly
A pull request is not a single event.
A developer can push new commits after opening the pull request.
For example:
Pull Request Opened
|
v
Commit Added
|
v
Pull Request Updated
|
v
Validation Runs Again
If your application validates code, the synchronize event can be important because it indicates that the pull request's branch changed.
The processing system should also avoid assuming that the first event represents the final state of the pull request.
When work is queued, consider whether processing the latest repository state is more important than processing every historical event individually.
Retry Failed Processing
Webhook reception and webhook processing are separate reliability concerns.
The webhook endpoint may successfully receive an event while the background worker later fails.
For example:
Webhook received
|
v
Queued successfully
|
v
Worker starts
|
v
External service unavailable
|
v
Processing fails
The worker should use an appropriate retry strategy for transient failures.
Do not retry every error indefinitely.
A useful classification is:
Transient error
-> Retry
Permanent validation error
-> Record failure
Invalid event
-> Reject or ignore
Duplicate event
-> Ignore safely
This makes failure handling more predictable.
Common Mistakes
Polling too frequently
A short polling interval does not make the architecture event-driven.
It simply creates more API requests.
Trusting the webhook payload
Always validate the webhook request before acting on its content.
Performing expensive work in the HTTP request
Return the webhook response quickly and move long-running work to a queue.
Ignoring duplicate delivery
Design processing to tolerate repeated events.
Subscribing to every available event
Only subscribe to events that your application actually needs.
Storing webhook secrets in source code
Use protected configuration.
Returning errors for events that do not require processing
Not every event needs to trigger work. Filter events early and keep the processing path focused.
Best Practices
Use webhooks when the external platform provides suitable events.
Subscribe only to the events your application needs.
Validate the webhook signature before trusting the payload.
Keep the webhook endpoint fast.
Queue long-running processing.
Make event processing idempotent.
Store delivery identifiers when duplicate handling matters.
Add retries for transient downstream failures.
Log event identifiers and processing status for troubleshooting.
Protect webhook secrets through secure configuration.
Monitor failed webhook deliveries and background processing separately.
Test the webhook endpoint with realistic event payloads.
Advantages
An event-driven GitHub integration provides several benefits:
It removes unnecessary polling requests.
It reduces the delay between an event and application processing.
It scales better when many repositories or pull requests are involved.
It creates a clear separation between event reception and background processing.
It makes integrations easier to connect to queues and workflow systems.
It can reduce unnecessary API usage.
The architecture is particularly useful for applications that need to respond quickly to repository activity.
Disadvantages and Limitations
Webhooks introduce their own operational responsibilities.
The application must expose an endpoint that can receive external traffic. That endpoint needs authentication or signature validation, monitoring, retry handling, and appropriate error management.
Webhook delivery also does not eliminate the need for state management. Applications may need to handle duplicate events, out-of-order processing, and events that arrive while previous work is still running.
For simple scripts that only need occasional information, polling may still be easier to implement.
The right choice depends on the workload and the capabilities of the external platform.
Troubleshooting Webhook Problems
Events are not arriving
Check that the webhook is configured for the correct repository and subscribed to the required event types.
The endpoint receives requests but rejects them
Check the webhook secret and signature validation logic.
Make sure the signature is calculated against the original request body.
Processing takes too long
Move expensive work out of the webhook request and into a background queue.
The same pull request is processed multiple times
Implement delivery-idempotency and verify that retries are not creating duplicate work.
Events arrive but the wrong action runs
Inspect the event header and the action value in the payload.
Different pull request events can have different actions.
Background processing fails
Separate webhook reception logs from worker logs. Check whether the failure is transient or permanent and apply the appropriate retry behavior.
Summary
Polling is easy to understand, but repeatedly asking GitHub whether a pull request changed is inefficient for applications that need near-event processing.
GitHub webhooks provide a better event-driven model. GitHub can notify an application when relevant pull request events occur, allowing the application to validate the request, identify the event, and queue the required work.
A production-ready implementation should validate webhook signatures, keep the HTTP endpoint fast, move long-running work to a queue, handle duplicate deliveries, and provide retry and monitoring mechanisms.
The important architectural shift is simple: instead of repeatedly asking whether something happened, let the system notify you when it happens. This makes pull request integrations cleaner, more responsive, and easier to scale.
Join the conversation! Your thoughts help the community grow.