Certainly! Here’s a robust Python script to consume messages from an AWS SQS FIFO queue at a constant rate, process them, and delete them. The script will handle processor crashes gracefully (e.g., via exception handling), and you can control the consumption rate using a simple rate limiter.
Assumptions:
- You have AWS credentials configured (via environment or
~/.aws/credentials).
- You have installed
boto3 (pip install boto3).
import boto3
import time
import random
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
# SQS client
sqs = boto3.client('sqs', region_name='us-east-1') # Change region as needed
QUEUE_URL = 'https://sqs.us-east-1.amazonaws.com/123456789012/your-queue.fifo' # Replace with your FIFO queue URL
# Rate limiting parameters
MESSAGES_PER_SECOND = 5 # Adjust as needed for your "constant rate"
SECONDS_PER_MESSAGE = 1.0 / MESSAGES_PER_SECOND
def process_message(message):
"""
Simulate message processing.
About 10% of the time, this function will 'crash' (raise an exception).
"""
if random.random() < 0.1:
raise RuntimeError("Simulated processor crash!")
# Simulate processing time
time.sleep(0.2)
logging.info(f"Processed message: {message['MessageId']}")
def main():
while True:
start_time = time.time()
try:
# Receive messages (max 10 at a time for FIFO)
response = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=1, # FIFO queues only support up to 10, but 1 is safest for strict ordering
WaitTimeSeconds=10, # Long polling
VisibilityTimeout=30 # Adjust as needed
)
messages = response.get('Messages', [])
if not messages:
logging.info("No messages received. Waiting...")
for message in messages:
try:
process_message(message)
# Delete message after successful processing
sqs.delete_message(
QueueUrl=QUEUE_URL,
ReceiptHandle=message['ReceiptHandle']
)
logging.info(f"Deleted message: {message['MessageId']}")
except Exception as e:
logging.error(f"Error processing message {message['MessageId']}: {e}")
# Message will become visible again after VisibilityTimeout
except Exception as e:
logging.error(f"Error receiving messages: {e}")
# Rate limiting
elapsed = time.time() - start_time
sleep_time = max(0, SECONDS_PER_MESSAGE - elapsed)
time.sleep(sleep_time)
if __name__ == "__main__":
main()
Key Points:
- Constant Rate: The script enforces a constant rate by sleeping for the appropriate time after each message.
- Crash Handling: If
process_message crashes, the message is not deleted and will reappear after the visibility timeout.
- FIFO: Only one message is processed at a time to maintain strict ordering (important for FIFO queues).
- Logging: All actions and errors are logged for monitoring.
You can adjust MESSAGES_PER_SECOND and other parameters as needed.
Let me know if you need a version with concurrency or batch processing!