Skip to content

fix: improve webhook reliability with timeout, break-to-continue, and explicit error status#3446

Open
Harshit-0018 wants to merge 4 commits intofossasia:devfrom
Harshit-0018:fix/webhook-reliability-improvements
Open

fix: improve webhook reliability with timeout, break-to-continue, and explicit error status#3446
Harshit-0018 wants to merge 4 commits intofossasia:devfrom
Harshit-0018:fix/webhook-reliability-improvements

Conversation

@Harshit-0018
Copy link
Copy Markdown
Contributor

@Harshit-0018 Harshit-0018 commented Apr 30, 2026

Summary

Fixes webhook reliability issues in app/eventyay/api/webhooks.py.

Changes

1. Replace break with continue in notify_webhooks (fixes #3400)

  • Previously, if a log entry lacked an organizer or webhook type, break would exit the entire loop, silently dropping all remaining entries in the batch
  • Now uses continue to skip only the problematic entry and process the rest
  • Added logger.debug() calls for skipped entries to aid troubleshooting

2. Add 30-second timeout to requests.post() in send_webhook (fixes #3398)

  • The outgoing HTTP request had no timeout parameter
  • If a remote webhook endpoint hangs, the Celery worker blocks indefinitely
  • Over time, enough hanging targets can exhaust the entire worker pool
  • Added WEBHOOK_TIMEOUT = 30 seconds constant

3. Add explicit success=False in error path

  • The RequestException handler was creating WebHookCall records without explicitly setting success=False, relying on the model default
  • Now both paths explicitly set the success field for consistency

Files Changed

  • app/eventyay/api/webhooks.py — 22 insertions, 3 deletions

Related Issues

Summary by Sourcery

Improve reliability and observability of outbound webhook delivery.

Bug Fixes:

  • Prevent webhook processing loop from terminating early when encountering log entries without an organizer or webhook type.
  • Avoid Celery workers hanging indefinitely on outbound webhook calls by adding a request timeout.
  • Ensure webhook call records consistently mark failures by explicitly setting the success flag on request exceptions.

… explicit error status

- Replace break with continue in notify_webhooks to prevent silently
  dropping remaining log entries when one entry lacks an organizer or
  webhook type (fixes fossasia#3400)
- Add 30-second timeout to requests.post() in send_webhook to prevent
  Celery worker pool exhaustion from hanging endpoints (fixes fossasia#3398)
- Add explicit success=False in RequestException error path for
  consistent WebHookCall records
- Add debug logging for skipped entries to aid troubleshooting
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Apr 30, 2026

Reviewer's Guide

Improves reliability and observability of webhook processing by skipping malformed log entries instead of aborting the loop, adding a request timeout to outbound webhook calls, and explicitly recording failure status on exceptions.

Sequence diagram for webhook notification dispatch and error handling

sequenceDiagram
    participant Caller as CeleryScheduler_or_App
    participant Notify as notify_webhooks
    participant DB as Database
    participant SendTask as send_webhook_task
    participant Worker as CeleryWorker
    participant Endpoint as WebhookEndpoint

    Caller->>Notify: notify_webhooks(logentry_ids)
    Notify->>DB: Query LogEntry by ids
    DB-->>Notify: LogEntry queryset

    loop For_each_logentry
        alt Missing_organizer
            Notify->>Notify: logger.debug(skip_no_organizer)
            Notify->>Notify: continue_to_next_logentry
        else Missing_notification_type
            Notify->>Notify: logger.debug(skip_no_webhook_type)
            Notify->>Notify: continue_to_next_logentry
        else Valid_logentry
            Notify->>DB: Get_or_cache_webhooks_for(organizer,action_type)
            DB-->>Notify: Webhook_list
            loop For_each_webhook
                Notify->>SendTask: send_webhook.apply_async(logentry_id, action_type, webhook_id)
            end
        end
    end

    par Webhook_delivery_for_each_task
        Caller->>Worker: Execute send_webhook(logentry_id, action_type, webhook_id)
        Worker->>DB: Load LogEntry, WebHook
        DB-->>Worker: Entities
        Worker->>Endpoint: HTTP POST payload (timeout=30s)
        alt HTTP_success
            Worker->>DB: WebHookCall.create(success=True, return_code=status_code)
        else HTTP_error_or_timeout
            Worker->>DB: WebHookCall.create(success=False, return_code=0)
            Worker->>Worker: self.retry(countdown=2**(retries*2))
        end
    end
Loading

File-Level Changes

Change Details Files
Make notify_webhooks robust to missing organizer or webhook type so one bad log entry does not stop processing the rest.
  • Replace break with continue when organizer is missing for a log entry
  • Replace break with continue when webhook_type is missing for a log entry
  • Add debug logging explaining why specific log entries are skipped
app/eventyay/api/webhooks.py
Prevent webhook workers from hanging indefinitely by adding a bounded HTTP timeout to webhook delivery.
  • Introduce WEBHOOK_TIMEOUT = 30 seconds constant for outbound webhook calls
  • Pass timeout=WEBHOOK_TIMEOUT to requests.post for webhook dispatch
app/eventyay/api/webhooks.py
Ensure webhook call records consistently mark failures explicitly when HTTP requests raise exceptions.
  • Set success=False when creating WebHookCall in RequestException handler rather than relying on model defaults
app/eventyay/api/webhooks.py

Assessment against linked issues

Issue Objective Addressed Explanation
#3398 Add a reasonable timeout (e.g., 30 seconds) to the requests.post() call in send_webhook so that webhook HTTP requests cannot hang Celery workers indefinitely.
#3398 Change webhook response handling so that the response body is streamed/limited before being fully loaded into memory, preventing large or malicious responses from causing excessive memory usage or OOM crashes. The PR adds a timeout and logging changes but does not modify how the response body is read. There is no change to use streaming or otherwise limit the response size before it is loaded into memory; the existing behavior of materializing the full response still appears to remain.
#3398 Explicitly set success=False when a RequestException occurs in send_webhook so that error paths are consistent with success paths in how they populate the WebHookCall record.
#3400 In notify_webhooks, replace the improper use of 'break' with 'continue' so that log entries without an organizer or webhook type are skipped while the remaining valid log entries in the batch are still processed.
#3400 Optionally improve observability for skipped webhook log entries (e.g., via logging) so that dropped entries are not silently ignored.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • Consider sourcing WEBHOOK_TIMEOUT from Django settings (or a config object) rather than a hard-coded module constant so deployments can tune the timeout without code changes.
  • The new debug logs in notify_webhooks might be useful at higher levels (e.g., info/warning) or augmented with organizer/event identifiers if these conditions indicate data inconsistencies that warrant operator attention.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider sourcing `WEBHOOK_TIMEOUT` from Django settings (or a config object) rather than a hard-coded module constant so deployments can tune the timeout without code changes.
- The new debug logs in `notify_webhooks` might be useful at higher levels (e.g., info/warning) or augmented with organizer/event identifiers if these conditions indicate data inconsistencies that warrant operator attention.

## Individual Comments

### Comment 1
<location path="app/eventyay/api/webhooks.py" line_range="335" />
<code_context>
+                    allow_redirects=False,
+                    timeout=WEBHOOK_TIMEOUT,
+                )
                 WebHookCall.objects.create(
                     webhook=webhook,
                     action_type=logentry.action_type,
</code_context>
<issue_to_address>
**suggestion:** Consider explicitly setting `success=True` on successful webhook calls for consistency.

Since the exception path now sets `success=False` explicitly, it would be clearer and more robust to also pass `success=True` on the success path, rather than relying on defaults or null, so `WebHookCall` consumers can always treat `success` as a concrete boolean.

Suggested implementation:

```python
                WebHookCall.objects.create(
                    webhook=webhook,
                    action_type=logentry.action_type,
                    return_code=resp.status_code,
                    payload=json.dumps(payload),
                    response_body=resp.text[: settings.MAX_SIZE_CONFIG[SizeKey.RESPONSE_SIZE_WEBHOOK]],
                    success=True,
                )

```

I can only see the exception-path `WebHookCall.objects.create(...)` in your snippet. The SEARCH block above assumes the success-path call looks like:

- Uses `resp.status_code` for `return_code`
- Uses `resp.text[: settings.MAX_SIZE_CONFIG[SizeKey.RESPONSE_SIZE_WEBHOOK]]` for `response_body`

If the actual success-path call differs (e.g., different variable names or slicing), update the SEARCH section to match your exact code and keep the `success=True` line in the REPLACE section. The key requirement is that the success-path `WebHookCall.objects.create(...)` includes `success=True` explicitly.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread app/eventyay/api/webhooks.py
@Harshit-0018
Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion @sourcery-ai!
Looking at the existing success path, it already explicitly computes success as a concrete boolean via the expression success=200 <= resp.status_code <= 299, which evaluates to True or False — so both paths now explicitly set the success field.
The key fix in this PR was the error/exception path (RequestException handler), which was previously omitting success entirely and relying on the model default. That's now addressed with the explicit success=False.
I believe both paths are now consistent and explicit. Happy to adjust if maintainers prefer a different approach!

@Harshit-0018
Copy link
Copy Markdown
Contributor Author

Updated as suggested — moved webhook timeout to settings for configurability.

@Harshit-0018
Copy link
Copy Markdown
Contributor Author

Addressed feedback and made timeout configurable via settings.
All checks passing. Ready for merge.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Improves outbound webhook delivery robustness in Celery tasks by preventing batch aborts on malformed log entries, adding a configurable HTTP timeout, and making failure recording more consistent.

Changes:

  • Skip individual log entries without organizer/event type using continue (and add debug logging) instead of aborting the whole batch with break.
  • Add a configurable webhook HTTP timeout via settings and apply it to outbound requests.
  • Limit webhook response body capture to a bounded size to reduce OOM risk, and explicitly record success=False on request exceptions.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
app/eventyay/config/settings.py Adds webhook_timeout config and exposes WEBHOOK_TIMEOUT for use by webhook delivery tasks.
app/eventyay/api/webhooks.py Fixes loop control in notify_webhooks, adds timeout + streamed/limited response reading in send_webhook, and explicitly marks failure records.

Comment thread app/eventyay/api/webhooks.py Outdated
try:
resp = requests.post(webhook.target_url, json=payload, allow_redirects=False)
max_body_size = settings.MAX_SIZE_CONFIG[SizeKey.RESPONSE_SIZE_WEBHOOK]
timeout = getattr(settings, "WEBHOOK_TIMEOUT", 30)
Comment on lines +330 to +342
resp = requests.post(
webhook.target_url,
json=payload,
allow_redirects=False,
timeout=timeout,
stream=True,
)
# Read only up to max_body_size bytes to prevent OOM
# from oversized responses before truncation
response_body = resp.raw.read(max_body_size).decode(
'utf-8', errors='replace'
)
resp.close()
Comment on lines 193 to +204
# Upload size limit in MB, needs to to in accordance with SizeKey
upload_size_csv: int = 1
upload_size_image: int = 10
upload_size_pdf: int = 10
upload_size_xlsx: int = 2
upload_size_favicon: int = 1
upload_size_attachment: int = 10
upload_size_mail: int = 4
upload_size_question: int = 20
upload_size_other: int = 10
response_size_webhook: int = 1
webhook_timeout: int = 30
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@Harshit-0018
Copy link
Copy Markdown
Contributor Author

Done with review and made the necessary changes as suggested by copilot.
All checks passing. Ready for merge.

@Rachit7168 Rachit7168 requested a review from Aqil-Ahmad May 4, 2026 09:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Backlog

2 participants