Best Practices

Follow these best practices to build reliable and efficient queue-based systems with RouteMQ.

Job Design

1. Keep Jobs Small and Focused

Each job should do one thing well:

# ✅ Good - focused job
class SendWelcomeEmailJob(Job):
    async def handle(self):
        await send_email(self.user_id, "welcome")

# ❌ Bad - doing too much
class UserSignupJob(Job):
    async def handle(self):
        await send_email()
        await create_profile()
        await setup_billing()
        await send_sms()

Why?

  • Easier to test and debug

  • Better error handling

  • Can retry individual steps

  • More flexible composition

2. Make Jobs Idempotent

Jobs should be safe to run multiple times:

Why?

  • Jobs may be retried on failure

  • Network issues can cause duplicates

  • Worker crashes might re-process jobs

3. Set Appropriate Timeouts

Guidelines:

  • API calls: 30-60 seconds

  • Data processing: 2-5 minutes

  • Report generation: 5-10 minutes

  • Don't exceed 10 minutes (consider breaking into smaller jobs)

4. Use Descriptive Names

Queue Organization

5. Use Different Queues for Different Priorities

Then run workers with appropriate settings:

6. Organize by Function

Data Handling

7. Don't Store Large Payloads

Why?

  • Keeps queue storage small

  • Reduces serialization overhead

  • Always gets fresh data

  • Avoids stale data issues

8. Handle Sensitive Data Carefully

Don't store passwords or tokens in job payloads:

9. Validate Data Before Dispatching

Error Handling

10. Always Implement failed()

11. Use Appropriate Retry Strategies

12. Log Appropriately

Monitoring

13. Monitor Queue Size

14. Track Processing Time

15. Monitor Failure Rates

Performance

16. Use Bulk Operations

17. Choose the Right Driver

18. Scale Workers Appropriately

Deployment

19. Use Process Managers

20. Regular Maintenance

Testing

21. Test Jobs in Isolation

22. Test with Limited Retries

Common Anti-Patterns

❌ Don't Block Workers

❌ Don't Chain Jobs Inside handle()

❌ Don't Store Job State in Class Variables

Checklist

Before deploying to production:

Summary

Do:

  • Keep jobs small and focused

  • Make jobs idempotent

  • Set appropriate timeouts

  • Use different queues for priorities

  • Store IDs, not large data

  • Handle sensitive data carefully

  • Implement failed() method

  • Monitor queue health

  • Use bulk operations

  • Test thoroughly

Don't:

  • Store large payloads

  • Store sensitive data

  • Chain jobs inside jobs

  • Block workers

  • Use class variables for state

  • Skip error handling

  • Forget to log

  • Ignore failed jobs

  • Over-complicate jobs

Next Steps

Last updated