Redis Pub/Sub (Publish/Subscribe) Created: 14 Jan 2026 Updated: 14 Jan 2026

Understanding CommandFlags in StackExchange.Redis

Deep Dive: Understanding CommandFlags in StackExchange.Redis

In the world of high-performance .NET applications, StackExchange.Redis stands out as the leading multiplexed client. A key feature that allows developers to fine-tune how commands are dispatched and processed is the CommandFlags enum.

CommandFlags are essentially "hints" or "directives" you give to the library's internal multiplexer. They dictate whether a command should wait for a response, which server it should target, and how it should behave in the internal command queue.

1. Execution Behavior Flags

These flags define the lifecycle of the request from the moment it leaves your application until the response (if any) is processed.

CommandFlags.None (The Default)

This is the standard operating mode. It follows a traditional Request-Response pattern.

  1. Behavior: The command is sent to the Redis server, and the library waits for the server to acknowledge and return the result.
  2. Performance: Involves a full network round-trip time (RTT).
  3. Use Case: Use this when the result is critical for your application logic (e.g., getting a configuration value, checking if a lock exists, or counting subscribers).
// Example: Relying on the result to drive logic
var subscriberCount = await _subscriber.PublishAsync("orders", "msg", CommandFlags.None);
if (subscriberCount == 0)
{
// Log that no one is listening
}

CommandFlags.FireAndForget

This flag optimizes for maximum throughput by ignoring the response entirely.

  1. Behavior: The command is written to the network buffer and the Task completes immediately. The library does not wait for Redis to process it or return an error.
  2. Performance: Extremely fast; eliminates waiting for RTT.
  3. Caveats: You will never receive an exception if the command fails on the server. The return value is always the default (usually 0 or null).
  4. Use Case: Non-critical logging, analytics, or background telemetry.
// Example: High-speed telemetry where losing a packet isn't fatal
await _db.StringSetAsync("stats:hits", "1", flags: CommandFlags.FireAndForget);

2. Priority and Queue Management

StackExchange.Redis uses internal queues to manage multiplexing. These flags help you manage "line-cutting."

CommandFlags.HighPriority

  1. Behavior: This flag tells the multiplexer to move this specific command to the front of the local pending queue.
  2. Impact: It bypasses other commands waiting to be sent over the same connection. Note that once the command reaches the Redis server, it is processed in the order it arrived relative to other clients.
  3. Use Case: Heartbeats, emergency system shutdowns, or high-priority circuit breaker triggers.
// Example: Sending a critical alert ahead of standard background tasks
await _db.PublishAsync("sys.alerts", "SHUTDOWN_IMMINENT", CommandFlags.HighPriority);

3. Routing and Topology Flags

In a Master/Replica (Slave) or Clustered setup, these flags determine which node actually receives the command.

CommandFlags.DemandMaster / PreferMaster

  1. DemandMaster: Forces the command to the Master node. If the Master is unavailable, the command fails.
  2. PreferMaster (Default): Tries the Master first but may fall back depending on configuration.
  3. Use Case: All Write operations automatically target the Master. Use these for reads that require strict consistency.

CommandFlags.DemandReplica / PreferReplica

(Note: Older versions used DemandSlave / PreferSlave)

  1. Behavior: Routes the command to a replica node. This offloads "Read" pressure from the Master.
  2. Use Case: Generating reports, heavy read operations where "eventual consistency" is acceptable.
FlagTargetFailure Policy
DemandMasterMasterThrows exception if Master is down
PreferReplicaReplicaFalls back to Master if Replicas are down

4. Advanced Utility Flags

FlagDescription
NoRedirectIn a Redis Cluster, this prevents the client from automatically following MOVED or ASK redirects. Useful for debugging specific nodes.
NoServerCertificateCustomValidationUsed in SSL/TLS scenarios to bypass specific certificate checks (use with caution).
DemandConnEnsures the command is only attempted if a connection is already established; prevents the command from waiting for a reconnection.

Summary and Best Practices

  1. Default to None: Unless you have a specific performance bottleneck, stick to CommandFlags.None to ensure your application handles errors and data integrity correctly.
  2. Use FireAndForget Judiciously: It is tempting for performance, but the lack of error handling can make debugging "missing data" issues very difficult.
  3. Scale with PreferReplica: If your application is Read-heavy, utilize PreferReplica to distribute the load across your Redis infrastructure.
  4. Avoid overusing HighPriority: If every command is high priority, none of them are. Use it only for genuine "out-of-band" signals.


Share this lesson: