Skip to main content
headers

Headers Exchange

Routing key: Ignored – routing based on message header attributes (key-value matching)

A headers exchange routes messages based on matching message header attributes rather than the routing key. Bindings specify key-value pairs and a match mode: 'x-match: all' requires all headers to match (AND), 'x-match: any' requires at least one header to match (OR). More flexible than topic but less commonly used due to overhead.

How it works

Headers exchanges ignore the routing key entirely and route based on a message's headers (AMQP 0-9-1 Basic Properties header table).

Binding definition: Each queue binding specifies a set of key-value pairs in the binding arguments. A special key 'x-match' controls match mode: 'x-match: all' – ALL specified headers must match (logical AND) 'x-match: any' – ANY one header must match (logical OR)

Message headers: publishers set arbitrary key-value pairs in the message headers property. The exchange compares these against all binding definitions.

When to use headers exchange: - Routing on multiple message attributes simultaneously (format AND version) - Content-type based routing (route PDF messages to PDF processor, CSV to CSV processor) - Multi-attribute subscriber filtering where topic wildcards are insufficient

Performance note: headers exchange is slower than direct or topic because it must compare header maps for each message. At high throughput, prefer topic exchange with a structured routing key.

The headers exchange was designed for cases where the routing logic is too complex to encode as a string. In practice, most teams use topic exchanges with structured routing keys and only reach for headers exchange for specific content-type routing scenarios.

Use Cases

  • Content-type routing – route by format='pdf' AND version='2' header combination

  • Priority routing by message attribute without encoding in routing key

  • Tenant-based routing – route by tenant-id header attribute

  • Multi-attribute subscriber filtering beyond what topic wildcards can express

Examples

Headers exchange with x-match: all (AND)
await ch.assertExchange('files', 'headers', { durable: true });

// PDF v2 processor – both format AND version must match
await ch.bindQueue('pdf.v2.processor', 'files', '', {
  'x-match': 'all',
  'format': 'pdf',
  'version': '2'
});

// Any PDF processor – only format must match
await ch.bindQueue('pdf.processor', 'files', '', {
  'x-match': 'any',
  'format': 'pdf'
});

// Publish with headers
ch.publish('files', '',  // routing key ignored
  Buffer.from(fileData),
  {
    headers: { format: 'pdf', version: '2', size: '1024' },
    contentType: 'application/pdf'
  }
);
// → delivered to pdf.v2.processor (all match) AND pdf.processor (any match)

See Also