Skip to content

⚡ Bolt: Offload blocking I/O to anyio in FastAPI routes#213

Open
anchapin wants to merge 1 commit intomainfrom
bolt-fastapi-anyio-offload-15037805867948622709
Open

⚡ Bolt: Offload blocking I/O to anyio in FastAPI routes#213
anchapin wants to merge 1 commit intomainfrom
bolt-fastapi-anyio-offload-15037805867948622709

Conversation

@anchapin
Copy link
Copy Markdown
Owner

@anchapin anchapin commented Mar 27, 2026

💡 What: Wrapped blocking synchronous operations (generator.generate, Path.read_bytes, Path.exists, generator._compile_pdf, etc.) in the api/main.py FastAPI routes with anyio.to_thread.run_sync (and functools.partial when arguments were needed).
🎯 Why: FastAPI's async def routes run on the main event loop. Any blocking synchronous call in these routes (like running pdflatex or reading files) stalls the entire application, making it unable to process other incoming concurrent requests. This causes significant performance degradation under load.
📊 Impact: Considerably improves concurrent performance by offloading CPU-bound or blocking I/O tasks to worker threads, freeing up the FastAPI event loop to handle hundreds of concurrent requests simultaneously.
🔬 Measurement: Run load tests using locust or wrk against the /v1/render/pdf or /v1/cover-letter API endpoints to observe improved throughput and decreased P99 latencies under concurrent load.


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

Summary by Sourcery

Offload blocking PDF generation and file I/O in FastAPI resume and cover-letter endpoints to background threads using anyio to prevent blocking the event loop and improve concurrency.

Enhancements:

  • Wrap synchronous PDF generation, LaTeX compilation, and file read/write operations in FastAPI routes with anyio.to_thread.run_sync to avoid blocking the async event loop.
  • Adjust resume YAML serialization to generate the YAML string in memory and write it via a non-blocking threaded file write.
  • Document the performance lesson about using anyio for blocking I/O in FastAPI in .jules/bolt.md for future optimizations.

Wraps blocking operations (PDF generation, file reads/writes, existence checks)
in FastAPI async routes using anyio.to_thread.run_sync to prevent event loop starvation
and improve concurrency performance.

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 27, 2026

Reviewer's Guide

Offloads blocking PDF generation and file I/O in FastAPI routes to worker threads using anyio, and documents this performance pattern in the Bolt playbook.

Sequence diagram for offloading blocking PDF rendering in FastAPI route

sequenceDiagram
    actor Client
    participant FastAPIRoute as FastAPIRoute_render_pdf
    participant Anyio as AnyioToThread
    participant Generator as TemplateGenerator
    participant FS as FileSystem
    participant PdfEngine as PdfCompilation

    Client->>FastAPIRoute: HTTP POST /v1/render/pdf
    FastAPIRoute->>FastAPIRoute: Create temp_path and output_pdf

    FastAPIRoute->>Anyio: run_sync(generator.generate, variant, pdf, output_pdf)
    Anyio->>Generator: generate(variant, output_format, output_path)
    Generator->>PdfEngine: invoke pdflatex
    PdfEngine-->>Generator: write PDF to output_pdf
    Generator-->>Anyio: return
    Anyio-->>FastAPIRoute: await completion

    FastAPIRoute->>Anyio: run_sync(output_pdf.exists)
    Anyio->>FS: exists(output_pdf)
    FS-->>Anyio: bool
    Anyio-->>FastAPIRoute: exists_result
    FastAPIRoute->>FastAPIRoute: Raise HTTP 500 if exists_result is False

    FastAPIRoute->>Anyio: run_sync(output_pdf.read_bytes)
    Anyio->>FS: read_bytes(output_pdf)
    FS-->>Anyio: pdf_bytes
    Anyio-->>FastAPIRoute: pdf_bytes

    FastAPIRoute-->>Client: HTTP 200 Response(pdf_bytes, application/pdf)
Loading

File-Level Changes

Change Details Files
Offload blocking PDF generation and file I/O in async FastAPI routes to anyio thread workers.
  • Wrap synchronous generator.generate calls in anyio.to_thread.run_sync with functools.partial to pass arguments
  • Run Path.exists and Path.read_bytes for generated PDFs via anyio.to_thread.run_sync to avoid blocking the event loop
  • Offload generator._compile_pdf and subsequent PDF file reads in the cover letter endpoint to anyio.to_thread.run_sync
  • Generate YAML as a string and write it via Path.write_text wrapped in anyio.to_thread.run_sync in the resume PDF endpoint
api/main.py
Document the anyio pattern for handling blocking I/O in FastAPI routes in the Bolt performance guide.
  • Add a new dated section describing the performance issue caused by blocking operations on the FastAPI event loop
  • Recommend wrapping blocking I/O-bound tasks with anyio.to_thread.run_sync and functools.partial when needed
.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:

  • You now have several repeated anyio.to_thread.run_sync(functools.partial(...)) call sites; consider extracting a small helper (e.g. run_in_thread(fn, *args, **kwargs)) to reduce duplication and make future changes to threading behavior centralized.
  • For the quick Path.exists and Path.read_bytes checks, you might consider grouping related filesystem work into a single threaded function (e.g. generate-and-read) to avoid multiple thread hops per request and keep the I/O pattern easier to reason about.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- You now have several repeated `anyio.to_thread.run_sync(functools.partial(...))` call sites; consider extracting a small helper (e.g. `run_in_thread(fn, *args, **kwargs)`) to reduce duplication and make future changes to threading behavior centralized.
- For the quick `Path.exists` and `Path.read_bytes` checks, you might consider grouping related filesystem work into a single threaded function (e.g. generate-and-read) to avoid multiple thread hops per request and keep the I/O pattern easier to reason about.

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