Projects/firestore-cli/Architecture

Architecture of firestore-cli

How the CLI keeps command concerns separate from a shared Firestore execution layer built around bounded concurrency, streaming, pagination, and backpressure.

On this page

Firestore CLI is designed as a Unix-oriented command-line tool with a small set of composable commands backed by a shared Firestore execution layer.

The architecture is intentionally split between command concerns (argument parsing, validation, formatting, terminal UX) and data-processing concerns (querying, discovery, concurrency, writes, deletes, and streaming).

Overview

At a high level, a command follows this path:

mermaid
CLI inputArgument parsingCommand validationFirestore operationQuery / discoveryWork schedulingExecutionOutput / stdin pipeline
View source
flowchart TD
  A[CLI input] --> B[Argument parsing]
  B --> C[Command validation]
  C --> D[Firestore operation]
  D --> E[Query / discovery]
  D --> F[Work scheduling]
  D --> G[Execution]
  E --> H[Output / stdin pipeline]
  F --> H
  G --> H

Commands are designed to work independently, but they can also be chained through standard Unix pipes.

For example:

bash
1firestore-cli query users --where "status" "==" "inactive" \
2 | firestore-cli delete --rate-limit 100

The first command produces document paths; the second consumes those paths from stdin.


Core Design Principles

1. Unix composability

Firestore CLI treats the shell as part of the application.

Commands should be useful on their own, but their output should also be consumable by another command or standard Unix utility.

This is why operations such as query can produce document paths suitable for:

bash
1firestore-cli delete

or data can be streamed into tools such as:

bash
1jq
2grep
3awk

The CLI avoids requiring users to write custom scripts for common data-management workflows.

Input resolution: path, --file, or stdin

Commands that accept document paths resolve input in a fixed order:

  1. --file <path>, if provided.
  2. The positional <path> argument, if provided.
  3. Piped stdin, but only when neither of the above is given and stdin is not a TTY.

stdin is deliberately not read when an explicit path or file is supplied. Reading stdin first caused two problems:

  • A non-TTY stdin (scripts, CI) shadowed the path argument, so path-based get/delete calls failed.
  • Commands could block forever when the parent process left the stdin pipe open without sending EOF (for example, Node's child_process.exec).

Piping without a positional path is unaffected:

bash
1firestore-cli query users --where status == inactive | firestore-cli delete

2. Bounded concurrency

Firestore operations can involve a large number of independent documents.

Running every operation sequentially is unnecessarily slow, while creating an unbounded number of promises can overwhelm memory, Firestore, or the local process.

The execution layer therefore uses controlled concurrency.

Conceptually:

mermaid
DiscoveryWorker 1Worker 2Worker 3Worker NFirestoreConcurrency control
View source
flowchart TD
  D[Discovery] --> W1[Worker 1]
  D --> W2[Worker 2]
  D --> W3[Worker 3]
  D --> W4[Worker N]
  W1 --> F[Firestore]
  W2 --> F
  W3 --> F
  W4 --> F
  C[Concurrency control] -.-> W1
  C -.-> W2
  C -.-> W3
  C -.-> W4

The number of active operations can be controlled independently from the rate at which work is discovered.

3. Separate discovery from execution

Large operations are split into two logical phases:

mermaid
find documents / generate workDiscoveryWork queueWorkerWorkerWorkerWorkerExecution
View source
flowchart TD
  D[Discovery] -->|find documents / generate work| Q[Work queue]
  Q --> W1[Worker]
  Q --> W2[Worker]
  Q --> W3[Worker]
  Q --> W4[Worker]
  W1 --> E[Execution]
  W2 --> E
  W3 --> E
  W4 --> E

Discovery is responsible for determining what needs to be processed.

Workers are responsible for determining how that work is executed.

This separation allows the CLI to continue discovering work while existing workers process previously discovered documents.

It also makes concurrency control considerably easier to reason about than a single recursive operation that performs discovery and mutation at the same time.


Concurrency

Bulk operations use a worker-based execution model.

A producer discovers work and places it into a queue. Workers consume items from the queue and perform the corresponding Firestore operation.

mermaid
ProducerBlockingQueueWorker 1Worker 2Worker 3Worker 4Firestore
View source
flowchart TD
  P[Producer] --> Q[BlockingQueue]
  Q --> W1[Worker 1]
  Q --> W2[Worker 2]
  Q --> W3[Worker 3]
  Q --> W4[Worker 4]
  W1 --> F[Firestore]
  W2 --> F
  W3 --> F
  W4 --> F

BlockingQueue

The queue provides a boundary between work discovery and work execution.

Its role is to:

  • Buffer pending work
  • Allow producers and workers to operate independently
  • Prevent uncontrolled accumulation of pending operations
  • Coordinate asynchronous consumers

A bounded queue is particularly important for large collections because discovery can otherwise produce work faster than Firestore operations can consume it.

AsyncGate

AsyncGate provides concurrency control around asynchronous operations.

Rather than allowing an arbitrary number of Firestore requests to execute simultaneously, the gate limits the number of active operations.

This provides a predictable upper bound on in-flight work.

Conceptually:

mermaid
Incoming workAsyncGateOperation AOperation BOperation CFirestore
View source
flowchart TD
  I[Incoming work] --> G[AsyncGate]
  G --> A[Operation A]
  G --> B[Operation B]
  G --> C[Operation C]
  A --> F[Firestore]
  B --> F
  C --> F

Concurrency and rate limiting are separate concerns.

  • Concurrency controls how many operations are in flight.
  • Rate limiting controls how frequently operations are started.

Keeping these concerns separate makes it possible to tune throughput without coupling worker count to an operations-per-second limit.


Query Pipeline

The query command has several stages before documents reach the output stream.

mermaid
CLI argumentsArgument parserWhere expressionBoolean expression parserFirestore queryDocument resultsOutput formatterstdout
View source
flowchart TD
  A[CLI arguments] --> B[Argument parser]
  B --> C[Where expression]
  C --> D[Boolean expression parser]
  D --> E[Firestore query]
  E --> F[Document results]
  F --> G[Output formatter]
  G --> H[stdout]

Boolean expressions

The --where interface supports compound conditions rather than requiring every query to be represented as a single filter.

For example:

bash
1firestore-cli query users \
2 --where "age" ">" 30 \
3 "AND" \
4 "status" "==" "active"

The parser converts the command-line representation into a structured expression before it reaches the Firestore query layer.

This keeps command-line syntax separate from Firestore's query API.

Argument parsing

Values are interpreted with a JSON-first strategy.

This allows structured values such as:

bash
1'{"active":true}'

while also supporting convenient CLI-oriented values such as:

text
1male,female

The goal is to preserve JSON's expressive power without forcing users into excessive shell quoting for common values.


Streaming

Large reads can be performed as a stream rather than accumulating the complete result set in memory.

mermaid
FirestoreResult streamFormatterstdoutterminalpageranother process
View source
flowchart TD
  F[Firestore] --> R[Result stream]
  R --> M[Formatter]
  M --> S[stdout]
  S --> T[terminal]
  S --> P[pager]
  S --> O[another process]

This is particularly useful for collections containing a large number of documents.

For example:

bash
1firestore-cli get users --stream | jq '.email'

The important property here is that downstream processing can begin while additional documents are still being retrieved.

Streaming also makes the CLI naturally compatible with Unix pipelines.


Pager and Backpressure

Interactive output presents a different problem from normal pipe output.

If a command produces data faster than the terminal can consume it, continuing to fetch data unnecessarily can cause excessive buffering and memory usage.

The pager integration therefore accounts for the consumer's ability to accept more output.

Conceptually:

mermaid
consumer cannot accept moreconsumer resumesFirestoreData streamPager / terminalPauseContinue
View source
flowchart TD
  F[Firestore] --> D[Data stream]
  D --> P[Pager / terminal]
  P -->|consumer cannot accept more| X[Pause]
  X -->|consumer resumes| C[Continue]
  C --> P

When the user pauses or stops consuming output, the CLI can stop pulling additional data until the output path is ready to continue.

This is especially important for commands operating on large collections.

The pager also has to coordinate with interactive CLI elements such as progress indicators and spinners. Those elements are stopped or handed off before the pager takes control of the terminal so that multiple components do not compete for cursor control.


Pagination

Firestore queries may return data across multiple pages.

The CLI abstracts pagination so commands can operate on the logical result set rather than requiring users to manually manage individual Firestore pages.

For deeper navigation, the CLI exposes --start-after.

For ordered queries:

mermaid
QueryPage 1Last document / cursor--start-afterPage 2
View source
flowchart TD
  Q[Query] --> P1[Page 1]
  P1 --> C[Last document / cursor]
  C --> S[--start-after]
  S --> P2[Page 2]

Multiple ordering fields can be used where supported by the underlying Firestore query.

Pagination is particularly useful for large collections and workflows where processing needs to resume from a known position.


Bulk Writes and Deletes

Bulk mutations follow the same general discovery/execution model.

mermaid
InputPath argumentFilestdinValidationWork queueWorkerWorkerWorkerFirestore
View source
flowchart TD
  I[Input] --> PA[Path argument]
  I --> FL[File]
  I --> SD[stdin]
  PA --> V[Validation]
  FL --> V
  SD --> V
  V --> Q[Work queue]
  Q --> W1[Worker]
  Q --> W2[Worker]
  Q --> W3[Worker]
  W1 --> F[Firestore]
  W2 --> F
  W3 --> F

This allows the same execution infrastructure to be reused across different input sources.

For example:

bash
1firestore-cli query users --where "status" "==" "inactive" \
2 | firestore-cli delete --rate-limit 100

The query process does not need to know how the downstream delete operation works. It only needs to produce a compatible stream of document paths.


Rate Limiting

Rate limiting is intentionally separate from worker concurrency.

A simplified model is:

mermaid
WorkRate limiterAsyncGateWorkers
View source
flowchart TD
  W[Work] --> R[Rate limiter]
  R --> G[AsyncGate]
  G --> WK[Workers]

This provides two independent controls:

ControlPurpose
ConcurrencyMaximum number of active operations
Rate limitMaximum operation start rate

This distinction matters for bulk workloads. Increasing concurrency can improve throughput when operations are latency-bound, while a rate limit can prevent the CLI from issuing requests faster than the surrounding workload should allow.


Output

The CLI supports several output modes depending on the command and workflow.

The primary goal is to make output useful both for humans and other programs.

Human-readable output

Designed for interactive terminal use, including pager support for large results.

JSON

Useful when a complete JSON representation is required:

bash
1firestore-cli get users/alice --json

JSONL

Newline-delimited JSON is useful for streaming and Unix pipelines:

json
1{"id":"alice","name":"Alice"}
2{"id":"bob","name":"Bob"}
3{"id":"charlie","name":"Charlie"}

Each document can be processed independently without requiring the receiving process to parse one large JSON array.


Full Document Paths

Firestore CLI can include the complete Firestore document path in structured output.

For example:

text
1projects/my-project/databases/(default)/documents/users/alice

This is useful when output from one command becomes input to another.

A query can therefore act as a discovery stage:

mermaid
querydocument pathsdelete / get / set
View source
flowchart LR
  Q[query] --> P[document paths]
  P --> D[delete / get / set]

The --full-path option exposes this metadata when needed.


Command Architecture

Commands are intentionally thin.

A command is primarily responsible for:

  1. Parsing its arguments
  2. Validating command-specific input
  3. Selecting the appropriate operation
  4. Formatting the result
  5. Handling terminal interaction

The lower-level execution layer handles concerns such as:

  • Firestore access
  • Pagination
  • Work scheduling
  • Concurrency
  • Streaming
  • Rate limiting

This separation helps prevent individual commands from implementing their own versions of the same execution logic.

It also makes new commands easier to add without duplicating the concurrency and streaming infrastructure.


Error Handling

Errors should remain actionable at the CLI boundary.

The general flow is:

mermaid
Underlying errorOperation layerCommand boundaryHuman-readable errorAppropriate process exit
View source
flowchart TD
  U[Underlying error] --> O[Operation layer]
  O --> B[Command boundary]
  B --> H[Human-readable error]
  B --> E[Appropriate process exit]

The CLI should avoid exposing unnecessary internal implementation details when reporting errors to users.

Debug logging is available through:

bash
1firestore-cli --debug <command>

This provides additional information when diagnosing failures.


Design Tradeoffs

The architecture intentionally favors controlled throughput and predictable resource usage over maximum theoretical concurrency.

Some operations could be made faster by simply creating more concurrent requests, but unbounded concurrency introduces problems:

  • Increased memory usage
  • Excessive pending promises
  • Greater pressure on Firestore
  • Less predictable behavior
  • Harder failure recovery

Similarly, streaming introduces additional coordination between producers and consumers, but avoids the much larger cost of buffering entire collections.

The architecture therefore treats:

concurrency, rate limiting, streaming, pagination, and backpressure as separate mechanisms.

This makes the behavior easier to tune and reason about as workloads grow.


Future Direction

The architecture is designed to leave room for additional Firestore workflows without forcing each command to reinvent the underlying execution model.

Potential areas for future development include:

  • Additional bulk operations
  • More output formats
  • Improved query ergonomics
  • Additional streaming workflows
  • More granular concurrency controls
  • Better progress reporting
  • Additional Firestore resource types

The goal is to keep the CLI simple at the surface while allowing the underlying execution engine to handle increasingly demanding workloads.