Guides

Best Practices


1. Keep Tasks Focused

Good: Single responsibility

1
#[task(name = "validate_email")]
2
pub async fn validate_email(
3
_ctx: TaskContext,
4
email: String,
5
) -> Result<bool> {
6
Ok(email.contains('@'))
7
}

2. Use Descriptive Names

1
// ✔ Good: Clear intent
2
#[task(name = "charge_credit_card_stripe")]
3
#[task(name = "reserve_inventory_item")]
4
#[task(name = "send_order_confirmation_email")]
5
6
// ❌ Bad: Vague names
7
#[task(name = "process")]
8
#[task(name = "handle_data")]
9
#[task(name = "do_stuff")]

3. Configure Appropriate Timeouts

1
// ✔ Good: Match timeout to expected duration
2
#[task(name = "quick_validation", timeout_mins = 1)]
3
#[task(name = "batch_import", timeout_mins = 30)]
4
#[task(name = "ml_training", timeout_mins = 180)]
5
6
// ❌ Bad: No timeout for long operations
7
#[task(name = "video_encoding")] // Could run forever

4. Design for Idempotency

Always use idempotency keys or check-before-execute patterns to ensure tasks can be safely retried.

5. Send Heartbeats for Long Operations

Send periodic heartbeats to prevent timeout and provide progress visibility.

6. Handle Cancellation Gracefully

Always check for cancellation in long-running tasks and clean up resources properly.

7. Use Type-Safe Inputs and Outputs

Define clear types for task inputs and outputs to catch errors at compile time.


Next Steps