Skip to content

Latest commit

 

History

History

examples

Folders and files

README.md

Queuack Examples

This directory contains practical examples demonstrating Queuack's features from basic to advanced use cases.

Quick Start

# Install Queuack
pip install queuack

# Run a basic example
python 01_basic/simple_queue.py

# Start a worker
python 02_workers/single_worker.py

Directory Structure

01_basic/ - Getting Started

Learn the fundamentals: enqueue, claim, ack, priorities, delays, and batch operations.

Start here if you're new to Queuack.

  • simple_queue.py - Basic producer/consumer pattern
  • priority_jobs.py - Priority-based job ordering
  • delayed_jobs.py - Schedule jobs for future execution
  • batch_enqueue.py - Efficiently enqueue multiple jobs

02_workers/ - Worker Patterns

Understand how to build robust worker processes with concurrency, multi-queue support, and graceful shutdown.

  • single_worker.py - Basic long-running worker
  • concurrent_workers.py - Multi-threaded parallel execution
  • multi_queue_worker.py - Process multiple queues with priorities
  • graceful_shutdown.py - Handle signals properly

03_dag_workflows/ - DAG Patterns

Master complex workflows with dependencies, parallel execution, and conditional logic.

  • linear_pipeline.py - Simple A → B → C pipeline
  • fan_out_fan_in.py - Parallel processing with synchronization
  • conditional_execution.py - OR-based dependencies (ANY mode)
  • diamond_dependency.py - Diamond pattern synchronization
  • external_dependencies.py - Reference external jobs

04_advanced/ - Advanced Patterns

Advanced techniques for production deployments and monitoring.

  • 01_custom_backpressure.py - Custom backpressure thresholds and adaptive policies
  • 02_monitoring_dashboard.py - Real-time web monitoring dashboard (Chart.js, WebSocket)
  • 03_distributed_workers.py - Multi-machine worker deployment
  • 04_run_strategies.py - Advanced retry and backoff strategies
  • 05_dag_visualization.py - Generate DAG diagrams (Mermaid)
  • 06_custom_colors.py - Custom Mermaid color schemes (6 themes)

05_real_world/ - Real-World Use Cases

Production-ready patterns organized by domain:

  • 01_etl/ - ETL & Data Pipelines (streaming, Spark, multi-format)
  • 02_web/ - Web scraping, async APIs, image processing
  • 03_ml/ - ML pipelines, hyperparameter tuning, experiment tracking
  • 04_integration/ - Framework integration (Flask, FastAPI, Django, CLI)

See each subfolder for detailed examples and README.

Running Examples

Basic Queue Example

cd 01_basic
python simple_queue.py

Worker Example

# Terminal 1: Enqueue jobs
python -c "
from queuack import DuckQueue
queue = DuckQueue('test.db')
for i in range(10):
    queue.enqueue(lambda x: print(x), args=(i,))
"

# Terminal 2: Run worker
cd 02_workers
python single_worker.py

DAG Example

cd 03_dag_workflows
python linear_pipeline.py

# Then start worker to process the DAG
python ../02_workers/single_worker.py

Real-world ETL Pipeline

cd 05_real_world/01_etl
python streaming_etl.py

# Monitor progress (optional)
cd ../../04_advanced
python 02_monitoring_dashboard.py

Best Practices

1. Function Picklability

Functions must be module-level (not lambdas or nested):

# ✓ Good
def process_data(x):
    return x * 2

queue.enqueue(process_data, args=(5,))

# ✗ Bad
queue.enqueue(lambda x: x * 2, args=(5,))  # Won't pickle!

2. Error Handling

Always set appropriate max_attempts and timeout_seconds:

queue.enqueue(
    flaky_api_call,
    max_attempts=5,        # Retry up to 5 times
    timeout_seconds=300    # 5 minute timeout
)

3. Backpressure

Use check_backpressure=True for producer throttling:

try:
    queue.enqueue(task, check_backpressure=True)
except BackpressureError:
    # Queue is full, slow down!
    time.sleep(10)

4. DAG Dependencies

Use named nodes for readability:

with queue.dag("pipeline") as dag:
    extract = dag.enqueue(extract_func, name="extract")
    transform = dag.enqueue(
        transform_func,
        name="transform",
        depends_on="extract"  # Use name, not job ID
    )

5. Worker Concurrency

Match concurrency to workload:

# CPU-bound tasks: concurrency = CPU cores
Worker(queue, concurrency=4)

# I/O-bound tasks: concurrency = 10-50
Worker(queue, concurrency=20)

Production Deployment

Multi-worker Setup

# Machine 1: Run worker
python -m queuack.worker --db=/shared/queue.db --concurrency=8

# Machine 2: Run worker
python -m queuack.worker --db=/shared/queue.db --concurrency=8

# Machine 3: Enqueue jobs
python producer.py

Docker Deployment

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

# Run worker
CMD ["python", "-m", "queuack.worker", "--db=/data/queue.db"]

Monitoring

# Use CLI tool
pip install queuack[cli]

# Check stats
queuack --db queue.db stats

# Monitor DAG
queuack --db queue.db dag-status 

# Start worker
queuack --db queue.db worker --concurrency=4

Testing Examples

All examples include inline tests. Run with pytest:

pytest 01_basic/
pytest 03_dag_workflows/
pytest --verbose  # Detailed output

Performance Tips

  1. Batch Operations: Use enqueue_batch() for bulk inserts
  2. Connection Pooling: One DB file per queue for hot paths
  3. Purge Old Jobs: Run queue.purge() regularly
  4. Index Optimization: Default indexes are sufficient for most cases
  5. Worker Placement: Colocate workers with data sources

Troubleshooting

Jobs stuck in "claimed" status

  • Worker crashed without releasing claim
  • Wait for claim timeout (default: 300s) or restart worker

High memory usage

  • Purge completed jobs regularly
  • Reduce worker concurrency
  • Process large data in chunks

Slow job claiming

  • Check database file location (SSD vs HDD)
  • Reduce job count via purging
  • Split into multiple queues

Contributing

Have a useful example? Submit a PR:

  1. Add to appropriate directory
  2. Include docstring and inline comments
  3. Add entry to this README
  4. Ensure code is self-contained and runnable

Support

License

All examples are MIT licensed - use them freely in your projects.