Queues decouple producers from consumers and support retries and load smoothing.
What It Does and When to Use It
Give each message an event ID and serializable payload. A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. At-least-once delivery implies idempotency; a queued job must carry enough stable identity to deduplicate.
Example 1: Basic Operation
Give each message an event ID and serializable payload.
<?php
$event=['event_id'=>bin2hex(random_bytes(16)),'type'=>'invoice.created','invoice_id'=>34];
$json=json_encode($event,JSON_THROW_ON_ERROR);
echo $json;
Example 2: Behavior and Validation
Validate deserialized messages before invoking business actions.
<?php
$message=json_decode('{"event_id":"evt-7","invoice_id":34}',true,512,JSON_THROW_ON_ERROR);
if (!isset($message['event_id'],$message['invoice_id'])) throw new UnexpectedValueException('Malformed job');
echo (int)$message['invoice_id'];
Practical Example: Application Use
Keep retry and dead-letter policy separate from message parsing.
<?php
$attempt=4;
$status=$attempt >= 5?'dead_letter':'retry';
echo 'Route delivery to: ', $status;
Important Behavior and Edge Cases
The second example highlights: Validate deserialized messages before invoking business actions. The practical example adds: Keep retry and dead-letter policy separate from message parsing.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Producer, consumer and scheduler | A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries. |
| Choosing safely | Acknowledge completed work and use idempotency to make retries safe. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Acknowledging a job before it finishes | Mark delivery successful only after durable processing succeeds. |
| Treating retries as harmless | Use idempotency keys and a bounded retry policy with dead-letter handling. |
| Skipping operational constraints | At-least-once delivery implies idempotency; a queued job must carry enough stable identity to deduplicate. |
Key Takeaways
- Queues decouple producers from consumers and support retries and load smoothing.
- Keep retry and dead-letter policy separate from message parsing.
- Acknowledge completed work and use idempotency to make retries safe.