You're on the right track with your approach to integrating a synchronous Pulsar client within an asynchronous FastAPI application. To effectively handle event producers in the background without blocking your main application flow, you can implement an asynchronous scheduler using asyncio.Queue and background tasks. This will allow you to enqueue Pulsar events and process them asynchronously, improving the responsiveness of your API endpoints.
Below is a comprehensive guide on how to achieve this, including modifications to your existing PulsarManager class and integration with FastAPI.
Overview
- Use
asyncio.Queue for Event Scheduling: Create separate queues for different types of Pulsar events (e.g., commands and updates).
- Background Worker Tasks: Implement background tasks that continuously consume from these queues and send events to Pulsar.
- Run Blocking I/O in Executors: Since Pulsar's
send method is synchronous, use asyncio's run_in_executor to prevent blocking the event loop.
- Integrate with FastAPI's Lifecycle: Ensure that background tasks are started when the application starts and are gracefully shut down.
Step-by-Step Implementation
1. Modify the PulsarManager Class
Enhance your PulsarManager to include asynchronous event handling using asyncio.Queue and background workers.
import enum
import uuid
from datetime import datetime
from decimal import Decimal
from typing import Dict, List, Literal, Optional, Union
import asyncio
import pulsar
from diamonds_domain.config import settings
from diamonds_domain.constants import ActionType
from pydantic import BaseModel, Field
# Existing class definitions (PulsarTopicType, PulsarCommandType, etc.) remain unchanged
class PulsarManager:
def __init__(self) -> None:
self._commands_topic = f"persistent://{settings.PULSAR_TENANT_NAME}/{settings.PULSAR_NAMESPACE}/{settings.PULSAR_COMMANDS_TOPIC_NAME}"
self._updates_topic = f"persistent://{settings.PULSAR_TENANT_NAME}/{settings.PULSAR_NAMESPACE}/{settings.PULSAR_UPDATES_TOPIC_NAME}"
self._client = pulsar.Client(
settings.PULSAR_SERVICE_URL,
authentication=pulsar.AuthenticationToken(settings.PULSAR_TOKEN),
)
self._commands_producer = self._client.create_producer(self._commands_topic)
self._updates_producer = self._client.create_producer(self._updates_topic)
self._type_to_producer_map = {
PulsarTopicType.COMMAND: self._commands_producer,
PulsarTopicType.UPDATE: self._updates_producer,
}
self._updates_subscription_name = f"updates-subscription-{uuid.uuid4()}"
self._commands_subscription_name = "commands-subscription"
self._commands_consumer = None
self._updates_consumer = None
# Initialize asyncio queues
self._command_queue: asyncio.Queue = asyncio.Queue()
self._update_queue: asyncio.Queue = asyncio.Queue()
# Event loop and background tasks
self._loop = asyncio.get_event_loop()
self._background_tasks: List[asyncio.Task] = []
def _get_producer(self, topic_type: PulsarTopicType):
return self._type_to_producer_map[topic_type]
def set_commands_consumer_with_callback(self, listener):
if self._commands_consumer is None:
self._commands_consumer = self._client.subscribe(
self._commands_topic,
self._commands_subscription_name,
pulsar.ConsumerType.Shared,
message_listener=listener,
)
def set_updates_consumer_with_callback(self, listener):
if self._updates_consumer is None:
self._updates_consumer = self._client.subscribe(
self._updates_topic,
self._updates_subscription_name,
pulsar.ConsumerType.Exclusive,
message_listener=listener,
)
def unsubscribe(self):
if self._updates_consumer:
self._updates_consumer.unsubscribe()
if self._commands_consumer:
self._commands_consumer.unsubscribe()
async def produce_update_async(self, event: PulsarUpdateEvent) -> None:
await self._update_queue.put(event)
async def produce_command_async(self, event: PulsarCommandEvent) -> None:
await self._command_queue.put(event)
async def _send_update(self, event: PulsarUpdateEvent):
data = event.model_dump_json()
producer = self._get_producer(PulsarTopicType.UPDATE)
await self._loop.run_in_executor(None, producer.send, data.encode("utf-8"))
async def _send_command(self, event: PulsarCommandEvent):
data = event.model_dump_json()
producer = self._get_producer(PulsarTopicType.COMMAND)
await self._loop.run_in_executor(
None, producer.send, data.encode("utf-8"), pulsar.SendResult(partition_key=str(event.payload.auth_user_uuid))
)
async def _command_worker(self):
while True:
event = await self._command_queue.get()
try:
await self._send_command(event)
except Exception as e:
# Handle exception (e.g., log it)
print(f"Failed to send command event: {e}")
# Optionally re-enqueue or handle retries
finally:
self._command_queue.task_done()
async def _update_worker(self):
while True:
event = await self._update_queue.get()
try:
await self._send_update(event)
except Exception as e:
# Handle exception (e.g., log it)
print(f"Failed to send update event: {e}")
# Optionally re-enqueue or handle retries
finally:
self._update_queue.task_done()
def start_background_tasks(self):
self._background_tasks.append(asyncio.create_task(self._command_worker()))
self._background_tasks.append(asyncio.create_task(self._update_worker()))
async def stop_background_tasks(self):
for task in self._background_tasks:
task.cancel()
await asyncio.gather(*self._background_tasks, return_exceptions=True)
self._background_tasks.clear()
async def wait_until_all_events_sent(self):
await self._command_queue.join()
await self._update_queue.join()
def produce_update(
self,
event: PulsarUpdateEvent,
) -> None:
asyncio.create_task(self.produce_update_async(event))
def produce_command(
self,
event: PulsarCommandEvent,
) -> None:
asyncio.create_task(self.produce_command_async(event))
# The synchronous produce_* methods can be deprecated or left for backward compatibility
def consume_update(self, msg) -> PulsarUpdateEvent:
try:
event = PulsarUpdateEvent.model_validate_json(msg.data().decode("utf-8"))
self._updates_consumer.acknowledge(msg)
return event
except Exception as e:
self._updates_consumer.negative_acknowledge(msg)
print(f"Failed to consume update event: {e}")
raise
def consume_command(self, msg) -> PulsarCommandEvent:
try:
event = PulsarCommandEvent.model_validate_json(msg.data().decode("utf-8"))
self._commands_consumer.acknowledge(msg)
return event
except Exception as e:
self._commands_consumer.negative_acknowledge(msg)
print(f"Failed to consume command event: {e}")
raise
pulsar_manager = None
def get_pulsar_manager():
global pulsar_manager
if pulsar_manager is None:
pulsar_manager = PulsarManager()
return pulsar_manager
2. Integrate with FastAPI's Lifecycle
Use FastAPI's startup and shutdown events to manage the background tasks.
from fastapi import FastAPI
from your_module import get_pulsar_manager # Adjust the import based on your project structure
app = FastAPI()
@app.on_event("startup")
async def startup_event():
manager = get_pulsar_manager()
manager.start_background_tasks()
@app.on_event("shutdown")
async def shutdown_event():
manager = get_pulsar_manager()
await manager.stop_background_tasks()
manager.unsubscribe()
manager._client.close()
3. Update Your API Endpoints
When producing events, use the asynchronous methods to enqueue events. This ensures that your API endpoints remain responsive.
from fastapi import APIRouter, Depends
from pydantic import UUID4
from uuid import uuid4
from decimal import Decimal
router = APIRouter()
@router.post("/create-profile")
async def create_profile(
auth_user_uuid: UUID4,
ref_code: str,
name: str,
referrer_uuid: Optional[UUID4] = None,
):
# Business logic to create a profile
# ...
# Create a PulsarCreateProfileEvent
event = PulsarCreateProfileEvent(
command=PulsarCommandType.CREATE_PROFILE,
auth_user_uuid=auth_user_uuid,
ref_code=ref_code,
name=name,
direct_referrer_uuid=referrer_uuid,
)
command_event = PulsarCommandEvent(payload=event)
# Enqueue the command event
manager = get_pulsar_manager()
manager.produce_command(command_event)
return {"message": "Profile creation initiated", "profile_uuid": str(uuid4())}
@router.post("/claim")
async def claim_action(
auth_user_uuid: UUID4,
action: ActionType,
value: Decimal,
idempotency_key: UUID4,
):
# Business logic to handle a claim
# ...
# Create a PulsarClaimEvent
event = PulsarClaimEvent(
command=PulsarCommandType.CLAIM,
action=action,
value=value,
auth_user_uuid=auth_user_uuid,
idempotency_key=idempotency_key,
)
command_event = PulsarCommandEvent(payload=event)
# Enqueue the command event
manager = get_pulsar_manager()
manager.produce_command(command_event)
return {"message": "Claim initiated"}
4. Handling Synchronous Listeners
Since Pulsar's message listeners are synchronous, if you need to process consumed messages asynchronously, you can integrate them similarly using background tasks or by delegating to an asynchronous processing pipeline. However, based on your original description, it seems your primary concern is with producers, which we've addressed above.
5. Optional: Implement Retries and Error Handling
For a production-ready system, you might want to implement retry mechanisms and more robust error handling. This can include exponential backoff, dead-letter queues, or logging to monitor failed events.
import logging
logger = logging.getLogger(__name__)
# Modify the worker methods to include retries
async def _command_worker(self):
while True:
event = await self._command_queue.get()
try:
await self._send_command(event)
except Exception as e:
logger.error(f"Failed to send command event: {e}")
# Implement retry logic or move to a dead-letter queue
finally:
self._command_queue.task_done()
async def _update_worker(self):
while True:
event = await self._update_queue.get()
try:
await self._send_update(event)
except Exception as e:
logger.error(f"Failed to send update event: {e}")
# Implement retry logic or move to a dead-letter queue
finally:
self._update_queue.task_done()
Benefits of This Approach
- Non-Blocking API Endpoints: By enqueueing events, your API responds immediately without waiting for Pulsar to process the event.
- Scalability: Background workers can be scaled or adjusted based on the queue size and processing speed.
- Error Isolation: Failures in event processing do not directly impact API responses.
- Flexibility: Easily extendable to handle more event types or integrate with other asynchronous systems.
Conclusion
By implementing an asynchronous event scheduling mechanism using asyncio.Queue and background tasks, you can efficiently manage Pulsar event production without blocking your FastAPI application. This ensures that your API remains responsive and can handle high-throughput scenarios gracefully.
Feel free to further customize the PulsarManager to fit the specific needs of your application, such as adding metrics, more sophisticated error handling, or integrating with monitoring systems.