Skip to content

⚡ Bolt: Offload blocking I/O operations to worker threads in async FastAPI routes#221

Open
anchapin wants to merge 1 commit intomainfrom
bolt-offload-blocking-io-18003314079667917910
Open

⚡ Bolt: Offload blocking I/O operations to worker threads in async FastAPI routes#221
anchapin wants to merge 1 commit intomainfrom
bolt-offload-blocking-io-18003314079667917910

Conversation

@anchapin
Copy link
Copy Markdown
Owner

@anchapin anchapin commented Mar 31, 2026

💡 What: Offloaded blocking synchronous operations (generator.generate, Path.exists, Path.read_bytes) in FastAPI endpoints render_pdf and render_resume_pdf to worker threads using anyio.to_thread.run_sync and functools.partial.
🎯 Why: FastAPI endpoints defined with async def run directly on the main async event loop. Executing blocking, CPU-bound tasks (like LaTeX PDF compilation in generator.generate) and synchronous file I/O operations on the main thread blocked the event loop. This caused a major concurrency bottleneck, completely starving the server from handling other incoming requests while a PDF was being generated or read.
📊 Impact: Significantly improves the API's concurrent request handling capabilities. The event loop is no longer blocked during expensive PDF generations and file reads, avoiding total server freezes under load.
🔬 Measurement: Verify by running load tests against the /v1/render/pdf or /v1/resumes/{id}/render/pdf endpoints. You should observe much better concurrent processing times without the server pausing entirely during individual request execution. Run test suite via python -m pytest to confirm everything works as expected.


PR created automatically by Jules for task 18003314079667917910 started by @anchapin

Summary by Sourcery

Offload blocking PDF generation and file I/O in async FastAPI PDF rendering endpoints to worker threads to improve concurrency and responsiveness.

Enhancements:

  • Run synchronous PDF generation and filesystem operations in render_pdf and render_resume_pdf via worker threads instead of the main event loop.

Documentation:

  • Document the performance impact and best practices for offloading blocking I/O in FastAPI async endpoints in the Bolt engineering notes.

In the FastAPI endpoints `render_pdf` and `render_resume_pdf`, synchronous, blocking operations such as `generator.generate()` (which performs CPU-bound tasks like LaTeX rendering), `output_pdf.exists()`, and `output_pdf.read_bytes()` were running on the main async event loop. This blocked the entire event loop, preventing the API from handling other concurrent requests effectively.

This commit offloads these blocking operations to a worker thread using `anyio.to_thread.run_sync()`. `functools.partial` is used to pass keyword arguments to `run_sync` for the `generator.generate` call. This ensures the main async event loop remains free to process concurrent requests, drastically improving API performance under load.

Co-authored-by: anchapin <6326294+anchapin@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Mar 31, 2026

Reviewer's Guide

Async FastAPI PDF rendering endpoints now offload blocking PDF generation and filesystem I/O to worker threads via anyio.to_thread.run_sync, improving event loop responsiveness, and the performance notes in .jules/bolt.md are updated with this pattern and its rationale.

Sequence diagram for async PDF rendering with worker thread offloading

sequenceDiagram
    actor Client
    participant FastAPI as FastAPIApp
    participant render_pdf as render_pdf_endpoint
    participant EventLoop as AsyncEventLoop
    participant AnyIO as anyio_to_thread
    participant Worker as WorkerThread
    participant Generator as TemplateGenerator
    participant FS as FileSystem

    Client->>FastAPI: HTTP POST /v1/render/pdf
    FastAPI->>EventLoop: schedule render_pdf
    EventLoop->>render_pdf: execute async handler

    render_pdf->>AnyIO: run_sync(generate_func)
    AnyIO->>Worker: execute generator.generate
    Worker->>Generator: generate(variant, output_format, output_path)
    Generator-->>Worker: PDF written to output.pdf
    Worker-->>AnyIO: return
    AnyIO-->>render_pdf: await result

    render_pdf->>AnyIO: run_sync(output_pdf.exists)
    AnyIO->>Worker: execute Path.exists
    Worker->>FS: check output_pdf
    FS-->>Worker: exists
    Worker-->>AnyIO: return bool
    AnyIO-->>render_pdf: exists
    render_pdf->>render_pdf: validate exists or raise HTTPException

    render_pdf->>AnyIO: run_sync(output_pdf.read_bytes)
    AnyIO->>Worker: execute Path.read_bytes
    Worker->>FS: read output_pdf bytes
    FS-->>Worker: content bytes
    Worker-->>AnyIO: return content
    AnyIO-->>render_pdf: content bytes

    render_pdf-->>FastAPI: Response(content=content, media_type=application/pdf)
    FastAPI-->>Client: HTTP 200 PDF response
Loading

File-Level Changes

Change Details Files
Offload blocking PDF generation and file I/O from async FastAPI endpoints to worker threads using anyio.to_thread.run_sync and functools.partial.
  • Wrap generator.generate invocations in partial with the appropriate keyword arguments and execute them via await anyio.to_thread.run_sync(...) instead of calling synchronously in async routes.
  • Replace direct Path.exists() checks with exists = await anyio.to_thread.run_sync(output_pdf.exists) and branch on the resulting boolean in async endpoints.
  • Replace direct Path.read_bytes() calls with content = await anyio.to_thread.run_sync(output_pdf.read_bytes) to avoid blocking the event loop during file reads in async handlers.
api/main.py
Document the performance learning about offloading blocking I/O in FastAPI and the chosen implementation pattern.
  • Add a new dated note describing how blocking CPU-bound work and filesystem I/O in async FastAPI endpoints degrade concurrency.
  • Record the action guideline to use anyio.to_thread.run_sync for synchronous work and functools.partial for passing keyword arguments to run_sync.
.jules/bolt.md

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

@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 left some high level feedback:

  • The render_pdf and render_resume_pdf endpoints now share nearly identical generate_func and to_thread.run_sync logic; consider extracting a small helper (e.g., async generate_pdf_to_path(...) or a generic async run_blocking(...)) to reduce duplication and keep future changes to the offloading behavior in one place.
  • Since anyio.to_thread.run_sync accepts *args/**kwargs, you could simplify the calls by passing arguments directly instead of constructing a functools.partial, which would make the offloading sites a bit more readable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `render_pdf` and `render_resume_pdf` endpoints now share nearly identical `generate_func` and `to_thread.run_sync` logic; consider extracting a small helper (e.g., `async generate_pdf_to_path(...)` or a generic `async run_blocking(...)`) to reduce duplication and keep future changes to the offloading behavior in one place.
- Since `anyio.to_thread.run_sync` accepts `*args`/`**kwargs`, you could simplify the calls by passing arguments directly instead of constructing a `functools.partial`, which would make the offloading sites a bit more readable.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant