Many development teams use scripts to monitor GitHub repositories and perform actions when something changes. For example, a script might check whether a pull request has been merged, whether new commits have been pushed, or whether all required checks have completed.
A common way to implement this is polling. The script sends requests to GitHub at regular intervals and checks whether the pull request has changed.
Although polling is easy to understand, it is not always the best approach. It creates repeated API requests, introduces unnecessary delays, and requires additional logic to handle failures and unexpected responses.
GitHub provides an alternative through pull request events and webhooks. Instead of continuously asking GitHub whether something has changed, an application can receive a notification when a particular event occurs.
This approach makes automation more efficient and easier to maintain.
In this article, we will explore how GitHub pull request events work, how to replace polling scripts with event-driven automation, how to configure webhooks, and what developers should consider when implementing this approach in production.
Why Polling Scripts Become Difficult to Maintain
Polling means checking a system repeatedly to determine whether a particular condition has changed.
For example, consider a deployment script that needs to know when a pull request has been merged.
A basic shell script might look like this:
#!/bin/bash
PR_NUMBER=125
while true; do
STATUS=$(gh pr view "$PR_NUMBER" \
--json state \
--jq '.state')
if [ "$STATUS" = "MERGED" ]; then
echo "Pull request merged."
break
fi
echo "Waiting for pull request..."
sleep 30
done
This script checks the pull request every 30 seconds.
There are several problems with this approach.
- Repeated API requests are made even when nothing changes.
- The application may take up to 30 seconds to detect a change.
- Network failures need to be handled.
- Scripts require timeout and retry logic.
- Multiple monitored pull requests increase the number of requests.
For a small personal project, polling might be sufficient. However, when several repositories and automation processes are involved, maintaining these scripts becomes more complicated.
An event-driven approach solves this problem by allowing GitHub to notify an application when a relevant activity occurs.
Understanding GitHub Pull Request Events
GitHub provides webhook events that notify external applications when activities occur in a repository.
A webhook is an HTTP callback. When a configured event occurs, GitHub sends an HTTP POST request to the endpoint registered by the application.
For pull request automation, the most relevant webhook event is pull_request.
This event supports different activity types.
| Activity type | When it occurs | Example use case |
|---|
| opened | A pull request is created | Start validation |
| synchronize | New commits are pushed | Run tests again |
| reopened | A closed pull request is reopened | Restart validation |
| closed | A pull request is closed | Check whether it was merged |
| ready_for_review | A draft becomes ready for review | Notify reviewers |
| review_requested | A reviewer is requested | Send a notification |
Instead of checking the pull request state continuously, an application can subscribe to the relevant activities.
For example, a deployment application only needs to receive the closed event and check whether the pull request was actually merged.
It does not need to monitor every pull request update.
How GitHub Webhooks Work
The webhook process follows a straightforward workflow.
<AsyncImage query="GitHub webhook event driven architecture repository pull request HTTP POST webhook receiver application processing workflow diagram" aspectRatio="16:9" width="100%"/>
The process works as follows:
- A developer creates or updates a pull request.
- GitHub identifies the activity associated with the pull request.
- GitHub generates a webhook payload.
- GitHub sends an HTTP POST request to the registered webhook endpoint.
- The application validates the request.
- The application processes the event.
- The application performs the required operation.
For example, when a pull request is merged, GitHub sends a pull_request event with the closed activity.
The payload contains information about the pull request, repository, sender, and merge status.
The receiving application can inspect the payload and decide whether to start a deployment, update a project management system, or notify another service.
Configuring a GitHub Pull Request Webhook
Before receiving webhook events, you need an application endpoint that GitHub can access.
For example, consider an ASP.NET Core application that receives pull request notifications.
First, open the GitHub repository settings.
Follow these steps:
- Open the repository on GitHub.
- Navigate to Settings.
- Select Webhooks.
- Click Add webhook.
- Enter the public URL of your webhook endpoint.
- Select application/json as the content type.
- Configure a webhook secret.
- Select the individual events you want to receive.
- Save the webhook configuration.
For this example, select Pull requests and subscribe to the required activity types.
Avoid subscribing to every repository event unless the application actually needs them.
Receiving Pull Request Events in ASP.NET Core
Now let's implement a basic webhook receiver using ASP.NET Core.
The application needs an endpoint that accepts incoming POST requests and reads the GitHub webhook payload.
Create a controller:
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
[ApiController]
[Route("api/github")]
public class GitHubWebhookController : ControllerBase
{
[HttpPost("webhook")]
public async Task<IActionResult> ReceiveWebhook(
CancellationToken cancellationToken)
{
using var document = await JsonDocument.ParseAsync(
Request.Body,
cancellationToken: cancellationToken);
var payload = document.RootElement;
var eventName = Request.Headers["X-GitHub-Event"]
.ToString();
if (eventName != "pull_request")
{
return Ok();
}
var action = payload
.GetProperty("action")
.GetString();
if (action == "closed")
{
var pullRequest = payload
.GetProperty("pull_request");
var isMerged = pullRequest
.GetProperty("merged")
.GetBoolean();
if (isMerged)
{
var number = payload
.GetProperty("number")
.GetInt32();
Console.WriteLine(
$"Pull request #{number} was merged.");
}
}
return Ok();
}
}
This endpoint reads the webhook event name and examines the pull request activity.
The important part is the merged property.
A pull request can be closed without being merged. Therefore, checking only whether the action is closed is not sufficient.
The application must also verify that the merged property is true.
This example demonstrates the event-processing logic. A production webhook receiver must additionally validate the webhook signature before trusting the payload.
Validating GitHub Webhook Signatures
Webhook security is important because the endpoint is publicly accessible.
Without verification, an attacker could send a fake request pretending to be GitHub and potentially trigger unauthorized operations.
GitHub supports webhook signature validation using a shared secret.
It sends the signature in the X-Hub-Signature-256 header.
The signature uses HMAC-SHA256, calculated from the raw request body and the configured webhook secret.
An ASP.NET Core helper can validate the signature:
using System.Security.Cryptography;
using System.Text;
public static class GitHubSignatureValidator
{
public static bool IsValid(
string payload,
string signature,
string secret)
{
if (!signature.StartsWith(
"sha256=",
StringComparison.OrdinalIgnoreCase))
{
return false;
}
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.ToLowerInvariant()));
}
}
The application should read the request body as raw text, validate the signature, and only then deserialize and process the payload.
Use a secret stored in a secure configuration provider rather than hardcoding it in the source code.
Also, verify the expected webhook event and repository identity before performing sensitive operations.
Handling Duplicate Webhook Deliveries
One important detail about webhooks is that applications must not assume every delivery will be processed exactly once.
GitHub provides delivery identifiers through the X-GitHub-Delivery header.
An application should use this identifier to detect duplicate deliveries.
For example, if GitHub retries a delivery because the previous attempt did not receive a successful response, the application should avoid executing the same operation twice.
A production implementation can maintain a table like this:
| Column | Purpose |
|---|
| DeliveryId | Unique webhook delivery identifier |
| EventName | Received event type |
| RepositoryId | Repository associated with the event |
| ReceivedAt | Time the application received the event |
| ProcessingStatus | Current processing state |
| ProcessedAt | Time processing completed |
Before processing a new delivery, check whether its delivery ID has already been recorded.
A database uniqueness constraint on DeliveryId can provide additional protection against concurrent duplicate requests.
For long-running operations, use a background processing system instead of keeping the webhook HTTP request open.
Processing Webhook Events Asynchronously
A webhook receiver should respond quickly.
For example, deploying an application, running integration tests, or synchronizing external systems may take several minutes.
Keeping the HTTP request open during these operations is not a good design.
A better architecture separates event reception from event processing.
The webhook receiver validates the signature, stores the event, and places a message in a background queue.
A worker then processes the event independently.
The architecture can look like this:
GitHub
|
v
Webhook Endpoint
|
v
Signature Validation
|
v
Duplicate Delivery Check
|
v
Message Queue
|
v
Background Worker
|
v
Deployment / Notification / Automation
For example, the application could use Amazon SQS, Azure Service Bus, or another reliable messaging system.
This approach improves reliability because webhook reception is separated from the actual business operation.
It also allows the application to retry failed processing without asking GitHub to send the original event again.
The queue consumer should still implement idempotent processing because messages can be delivered more than once.
GitHub Webhooks vs Polling
Both approaches have valid use cases, but they solve the problem differently.
| Comparison | Polling | GitHub Webhooks |
|---|
| Communication | Application requests updates | GitHub sends notifications |
| API requests | Repeated requests | Event-based delivery |
| Response time | Depends on polling interval | Usually near real-time |
| Infrastructure | Polling scheduler or script | Public webhook endpoint |
| Failure handling | Retry and timeout logic | Delivery handling and application retries |
| Scalability | Can increase API traffic | Better suited to event-driven integrations |
| Complexity | Simple for small scripts | Requires secure event processing |
Polling is still useful when an external system does not support webhooks or when an application needs to periodically reconcile its local state with GitHub.
Webhooks are generally preferable when the application needs to react to specific repository events.
Best Practices for Production Webhook Applications
Validate Every Incoming Request
Never trust a webhook payload simply because it contains GitHub-related information.
Validate the HMAC signature using the configured secret and inspect the event headers.
Make Event Processing Idempotent
Use the delivery ID to detect duplicate webhook requests.
Also make the actual business operation safe to repeat. For example, a deployment process should not accidentally deploy the same release multiple times because of duplicate event processing.
Respond Quickly
Avoid performing long-running tasks inside the webhook request.
Validate, persist, enqueue, and acknowledge the event before processing it in the background.
Monitor Failed Deliveries
Track incoming webhook requests, validation failures, processing errors, and retry attempts.
GitHub also provides webhook delivery information that helps developers investigate delivery problems.
Subscribe Only to Required Events
Receiving unnecessary events increases processing overhead.
Subscribe only to the activities required by the application.
Implement Reconciliation
Webhooks improve responsiveness, but applications should not assume that every event will always be delivered and processed successfully.
For important business operations, periodically reconcile the application's stored state with GitHub.
This provides an additional recovery mechanism for missed or failed processing.
Common Mistakes Developers Should Avoid
| Mistake | Why it causes problems | Better approach |
|---|
| Trusting webhook payloads without validation | Allows forged requests | Validate HMAC signatures |
| Treating every closed PR as merged | Can trigger incorrect deployments | Check pull_request.merged |
| Processing long operations inside the endpoint | Can cause timeouts | Use background workers |
| Ignoring duplicate deliveries | May execute operations multiple times | Track delivery IDs |
| Subscribing to every event | Creates unnecessary processing | Select required activities |
| Assuming webhooks never fail | Can leave application state outdated | Implement retries and reconciliation |
| Logging complete payloads | May expose sensitive information | Log only necessary fields |
Troubleshooting Common Webhook Problems
GitHub Is Not Delivering Events
Check the webhook configuration and verify that the correct repository events are selected.
Review the webhook delivery history and inspect the response status returned by the application.
Also ensure that the endpoint is publicly reachable over HTTPS.
Webhook Requests Return HTTP 401 or 403
Check whether the application is rejecting the request because of an invalid signature or incorrect secret.
Ensure that the signature is calculated from the original request body without modifying its contents.
The Same Pull Request Operation Runs Multiple Times
Inspect the X-GitHub-Delivery header and verify that duplicate deliveries are being handled correctly.
Also check whether the background processing system is retrying messages.
Pull Request Closure Triggers an Incorrect Deployment
Verify that the application checks both the closed action and the pull_request.merged property.
A closed pull request is not necessarily a merged pull request.
Webhook Processing Takes Too Long
Move long-running operations into a background queue.
The webhook endpoint should validate and record the event rather than executing the complete deployment or testing process.
Summary
Polling scripts are a straightforward way to monitor GitHub pull requests, but they become less efficient as repositories and automation requirements grow.
GitHub pull request webhooks provide an event-driven alternative. Instead of continuously checking whether a pull request has changed, applications receive notifications when activities such as opening, updating, reopening, or merging occur.
For production applications, signature validation, duplicate delivery handling, asynchronous processing, and event reconciliation are important parts of a reliable implementation.
GitHub Actions is another useful option when automation should run directly inside a repository without maintaining an external webhook receiver.
The right approach depends on the application. Polling can still be useful for periodic synchronization, GitHub CLI works well for terminal-based automation, and webhooks are a better fit for applications that need to respond to repository events.
By replacing unnecessary polling with event-driven processing, development teams can build more responsive and maintainable GitHub integrations.
Join the conversation! Your thoughts help the community grow.