This document explains the internal design and architecture of PowerQ.
It is intended for developers who want to understand or contribute to the scheduler’s internals.
PowerQ is a priority-based asynchronous task scheduler.
It manages tasks in two separate queues (priority and normal), enforces a concurrency limit, and ensures non-blocking execution using JavaScript’s event loop.
- Priority Queue (
priorityQ)
Stores tasks marked as high priority. - Normal Queue (
normalQ)
Stores tasks added by default (non-priority).
Each task is stored as a TaskRecord object containing:
id: unique identifierexec: the task function or promisepriority: boolean flagaddedAt: timestamp (used for custom logic like aging)canceled: whether the task was canceledcontroller:AbortControllerfor cancellationresolve/reject: hooks to settle the task’s result promisestate:"queued" | "running" | "completed"
The scheduler controls:
runningCount→ how many tasks are currently executingconcurrency→ maximum allowed concurrent tasksqueueSelector→ custom logic to decide whether to pick frompriorityQornormalQ
flowchart TD
A[Add Task] --> B{Priority?}
B -- Yes --> P[Push to priorityQ]
B -- No --> N[Push to normalQ]
P --> C[Drain Scheduler]
N --> C[Drain Scheduler]
C --> D{runningCount < concurrency?}
D -- No --> Stop[Wait]
D -- Yes --> E[Pick Task]
E -->|priorityQ first| Run[Execute Task]
Run --> F[Promise Resolves/Rejects]
F --> G[Resolve/Reject TaskHandle.result]
G --> H[Decrement runningCount]
H --> C
-
Continuously checks if there are free concurrency slots.
-
Always picks from:
queueSelector(if provided)- Otherwise → priorityQ first, then normalQ
-
Runs the task via
Promise.resolve().then(...). -
On completion:
- Resolves/rejects the promise
- Removes task from
tasksmap - Decrements
runningCount - Calls
_drain()again to pick the next task
- Each task has an
AbortController. - Calling
.cancel(taskId):- Removes the task from its queue if still queued
- Marks as canceled
- Calls
AbortController.abort() - Rejects the promise with
"Task canceled"
-
.promoteToPriority(taskId)Moves a queued task fromnormalQ→priorityQ. -
.demoteToNormal(taskId)Moves a queued task frompriorityQ→normalQ.
- Controlled via
runningCountandconcurrency. - User can change at runtime with
.setConcurrency(n). - Scheduler automatically fills free slots immediately.
- Uses Promises and async/await → works in Node, browser, React Native.
- Fallback
AbortControllerimplementation ensures compatibility even if not natively supported. - No dependencies.
- Non-blocking: No synchronous loops that block the event loop.
- Lightweight: Zero dependencies, minimal memory footprint.
- Extensible: User can plug in custom
queueSelectorstrategies. - Robust: Tasks can be canceled, promoted, demoted at any time.
- Multiple priority levels (beyond binary)
- Task timeouts
- Retry policies
- Metrics (avg wait time, throughput)