Skip to content

Add FastAPI background tasks integration example#171

Merged
chrisguidry merged 3 commits intomainfrom
fast-api-integration-example
Oct 24, 2025
Merged

Add FastAPI background tasks integration example#171
chrisguidry merged 3 commits intomainfrom
fast-api-integration-example

Conversation

@desertaxle
Copy link
Copy Markdown
Collaborator

@desertaxle desertaxle commented Oct 24, 2025

This example demonstrates how to integrate Docket with FastAPI for reliable background task processing. Includes comments explaining:

  • How to embed a Docket worker within a FastAPI application
  • FastAPI lifespan management for Docket/Worker lifecycle
  • Dependency injection pattern for accessing Docket in routes
  • Key advantages of Docket over FastAPI's built-in background_tasks

The example shows the pattern of scheduling tasks from API endpoints that return immediately while work is processed asynchronously by the background worker.

There might be an opportunity for something more out of the box here, but integration is straightforward enough that it may not be necessary.

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

This example demonstrates how to integrate Docket with FastAPI for reliable
background task processing. Includes comprehensive documentation explaining:

- How to embed a Docket worker within a FastAPI application
- FastAPI lifespan management for Docket/Worker lifecycle
- Dependency injection pattern for accessing Docket in routes
- Key advantages of Docket over FastAPI's built-in background_tasks
  (durability, horizontal scaling, advanced features, observability)

The example shows the pattern of scheduling tasks from API endpoints that
return immediately while work is processed asynchronously by the background
worker.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link
Copy Markdown
Contributor

claude bot commented Oct 24, 2025

Claude finished @desertaxle's task —— View job


Code Review for FastAPI Background Tasks Integration Example

Todo List

  • Read and analyze the FastAPI integration example
  • Review dependency changes
  • Check code quality and best practices
  • Identify potential bugs or issues
  • Assess performance considerations
  • Review security concerns
  • Evaluate test coverage requirements
  • Provide comprehensive feedback

Overall Assessment

This is a well-crafted example that effectively demonstrates how to integrate Docket with FastAPI for reliable background task processing. The code is clean, well-documented, and follows Python best practices. The extensive documentation clearly explains the advantages of using Docket over FastAPI's built-in background tasks.

Strengths

1. Excellent Documentation

  • Comprehensive docstring explaining the purpose and rationale (lines 1-58)
  • Clear comparison between Docket and FastAPI's built-in BackgroundTasks
  • Well-structured sections with clear headers and explanations
  • Practical usage instructions with curl example

2. Clean Code Structure

  • Logical organization with clearly separated sections
  • Proper use of FastAPI patterns (lifespan, dependency injection)
  • Good separation of concerns between web handling and task processing
  • Type hints used appropriately (Annotated, BaseModel)

3. Resource Management

  • Proper lifecycle management using FastAPI's lifespan context manager
  • Clean shutdown handling with task cancellation and CancelledError handling
  • Uses async context managers properly for both Docket and Worker

Areas for Improvement

1. Error Handling

The example lacks error handling in several critical areas:

  • Line 175: No error handling when scheduling the task with docket.add()
  • Lines 106-130: The lifespan function could benefit from more specific error handling
  • Line 142: get_docket() could raise AttributeError if app.state.docket doesn't exist

Recommendation: Add try-except blocks to handle potential Redis connection issues and task scheduling failures:

try:
    await docket.add(send_email)(user.email)
except Exception as e:
    # Log error and potentially return 503 Service Unavailable
    raise HTTPException(status_code=503, detail="Unable to schedule background task")

2. Security Considerations

  • Line 162: The password field is stored as plain text in the Pydantic model. While this is just an example, it might lead users to copy this pattern.

Recommendation: Add a comment warning about password handling:

password: str  # WARNING: In production, never store passwords as plain text

3. Performance Considerations

  • Line 118: Running the worker with run_forever() in the same process as the web server could impact request handling performance under heavy load.

Recommendation: Add a comment explaining the trade-offs:

# Note: In production, consider running workers in separate processes
# for better resource isolation and scaling capabilities

4. Missing Validation

  • Line 175: No validation that the email was actually scheduled successfully before returning 201

Recommendation: Consider returning the task ID or confirmation:

task_id = await docket.add(send_email)(user.email)
return {"message": "User created", "task_id": str(task_id)}

Test Coverage

Current Status

  • The example files are not covered by tests (checked tests/ directory)
  • As this is in the examples/ directory, it appears to be excluded from coverage requirements

Recommendation

While example files typically don't require test coverage, consider:

  1. Adding a simple smoke test to ensure the example remains functional
  2. Or explicitly excluding the examples/ directory from coverage reporting in pyproject.toml

Minor Suggestions

  1. Line 69: The import from common import run_redis assumes the example is run from the examples directory. Consider adding a note about this requirement.

  2. Line 86: The simulated delay of 1 second could be made configurable for testing purposes.

  3. Line 178: Returning nothing (return) works but might be more explicit with return {"message": "User created successfully"}

Dependencies Review

The additions to pyproject.toml (lines 65-69) are appropriate:

  • FastAPI, Pydantic, and Uvicorn are standard dependencies for this use case
  • Versions are properly specified
  • Dependencies are correctly placed in the examples group

Conclusion

This is a high-quality example that effectively demonstrates Docket's integration with FastAPI. The code is production-ready with minor enhancements suggested above. The clear documentation and practical approach make this a valuable addition to the project's examples.

Recommendation: ✅ Approve with minor suggestions

The PR successfully achieves its goal of demonstrating FastAPI integration. The suggested improvements are minor and could be addressed in a follow-up PR if desired.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Oct 24, 2025

📚 Documentation has been built for this PR!

You can download the documentation directly here:
https://github.com/chrisguidry/docket/actions/runs/18786079369/artifacts/4365272343

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Oct 24, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0ebb6c3) to head (8daa263).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff            @@
##              main      #171   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           34        34           
  Lines         4834      4834           
  Branches       265       265           
=========================================
  Hits          4834      4834           
Flag Coverage Δ
python-3.12 100.00% <ø> (ø)
python-3.13 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@desertaxle desertaxle marked this pull request as ready for review October 24, 2025 16:39
Copy link
Copy Markdown
Owner

@chrisguidry chrisguidry left a comment

Choose a reason for hiding this comment

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

THIS IS AWESOME

@chrisguidry chrisguidry merged commit 36f92a8 into main Oct 24, 2025
14 checks passed
@chrisguidry chrisguidry deleted the fast-api-integration-example branch October 24, 2025 19:04
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.

3 participants