skip to content

How is a MongoDB OP_MSG framed, what do the hello limits cap, and what does a 9.0 server check in its BSON?

level: middleimportance: nice to knowfreq 12%

answer

  1. 16-byte header, then flags, then sections
  2. which section kind carries the command
  3. one limit per document, one per message
  4. both limits come from the server
  5. structural check, not a conformance check

basics

~10 s

An OP_MSG is a 16-byte header, 4 flag bytes and sections holding BSON documents. hello's maxMessageSizeBytes caps the whole message and maxBsonObjectSize each document. MongoDB 9.0 always validates incoming BSON structurally, whatever net.wireObjectCheck says.

solid answer

~50 s

An `OP_MSG` starts with four `int32` fields: `messageLength`, `requestID`, `responseTo` and `opCode` 2013. Then come `flagBits` and one or more sections, each a kind byte plus payload. Kind 0 holds the one command document; kind 1 holds a size, an identifier and a run of documents, which is how a bulk insert avoids array keys. Everything is little-endian, and `messageLength` includes its own four bytes. The `hello` reply states the limits: `maxBsonObjectSize` is 16,777,216 bytes per document and `maxMessageSizeBytes` is 48,000,000 bytes per message, so two maximum documents fit in one message and three do not. Those limits belong to the server, not the BSON format. In 9.0, `net.wireObjectCheck` is deprecated and validation always runs, but its default mode is structural: lengths, type bytes, terminators. It does not look for duplicate names or bad UTF-8.

code

plaintext · 14 lines
plaintext
offset  bytes                 field
 0      33 00 00 00           messageLength = 51
 4      01 00 00 00           requestID = 1
 8      00 00 00 00           responseTo = 0
12      DD 07 00 00           opCode = 2013
16      00 00 00 00           flagBits = 0
20      00                    section kind 0
21      1E 00 00 00           document length = 30
25      10 70 69 6E 67 00     int32 element, key "ping"
31      01 00 00 00           value 1
35      02 24 64 62 00        string element, key "$db"
40      06 00 00 00           string length = 6, with NUL
44      61 64 6D 69 6E 00     "admin" and NUL
50      00                    document terminator

go deeper

for a junior

Recall that drivers and servers exchange BSON documents inside framed messages, that OP_MSG is the message type, and that a document and a whole message have separate size limits.

for a middle

Lay out the header, flags and section kinds, and add up a message's bytes, saying which lengths include their own prefix. Explain why a document sequence avoids array keys.

for a senior

Reason from the limits when a large batch fails or splits. Know that validation on arrival is structural only, so a clean insert does not prove a document conforms.

for a principal

Few teams should touch this layer directly. The judgment is knowing when wire details matter, such as for a proxy or a capacity estimate, and otherwise leaving framing to the driver.

## The frame `OP_MSG` is MongoDB's wire protocol message, opcode **2013**, introduced in 3.6. The current driver specification says all messages must use it. All integers are **little-endian**. | Part | Size | Meaning | |---|---|---| | `messageLength` | 4 | Total bytes in the message, **including these 4** | | `requestID` | 4 | Identifier of this message | | `responseTo` | 4 | `requestID` being answered, or 0 | | `opCode` | 4 | 2013 | | `flagBits` | 4 | `checksumPresent`, `moreToCome`, `exhaustAllowed` | | sections | variable | One or more, each a kind byte and a payload | | `checksum` | 0 or 4 | Optional CRC-32C, present only if flag bit 0 is set | ## Section kinds - **Kind 0, the body.** One BSON document, the command, whose size comes from the document's own leading `int32`. A message must have **exactly one**. The command name must be its first key, and `$db` travels here because the opcode has no database field. - **Kind 1, a document sequence.** A 4-byte `size`, which counts itself but not the kind byte, then a `cstring` identifier, then BSON documents placed end to end. The server accepts this for `documents` in `insert`, `updates` in `update` and `deletes` in `delete`. A BSON array would add a key such as `"0"` per element; a sequence carries none. - **Kind 2** is reserved for a server-internal security token, and drivers do not send it. - **Kind 3** is a request-only telemetry document, at most one per message, which senders gate on server support. An unknown kind must produce an error and close the socket. Sections may arrive in any order. ## Counting a message A `ping` against `admin` has one kind 0 section. The body `{ping: 1, $db: "admin"}` is 30 bytes: 4 for the length, 10 for the `int32` element (type byte, `ping` plus NUL in 5, value in 4), 15 for the string element (type byte, `$db` plus NUL in 4, length in 4, `admin` plus NUL in 6) and 1 for the terminator. The message is then 16 + 4 + 1 + 30 = **51 bytes**. An insert of two 14-byte documents using a sequence, with a 32-byte body, costs: 1. Header and flags: 20 bytes. 2. Kind byte and body: 1 + 32 = 33 bytes. 3. Kind byte: 1 byte. 4. Sequence: 4 (`size`) + 10 (`documents` plus NUL) + 14 + 14 = 42 bytes, the value `size` holds. 5. Total: 20 + 33 + 1 + 42 = **96 bytes**. ## The two limits A driver learns both from the `hello` reply. | Field | Default | Caps | Includes | |---|---|---|---| | `maxBsonObjectSize` | 16,777,216 (16 × 1024 × 1024) | One BSON document | Its own length prefix and trailing NUL | | `maxMessageSizeBytes` | 48,000,000 | One wire message | The 16-byte header and everything after it | - **Units:** one limit is binary and the other decimal. - **The boundary:** both are maximums, so a value exactly at the limit is permitted and one byte more is not. - **Batches:** two full-size documents total 33,554,432 bytes and fit in one message. Three total 50,331,648, which is over, so a driver has to split the batch. - **A third limit:** `maxWriteBatchSize` counts operations rather than bytes. These limits are **the server's, not the format's**. The BSON specification only gives a document an `int32` length. The r9.0.4 wire parser's own bound on a sequence document is 16 KiB looser, because `validateBSONObjSize()` defaults to the internal size, so that parser check is not the place the user limit is decided. ## What the server checks MongoDB 9.0 deprecates `net.wireObjectCheck` and its `--objcheck` and `--noobjcheck` flags. In r9.0.4 they are accepted and only log a deprecation warning: the option's description reads "Data validation is always performed". Before 9.0 the setting defaulted to `true` and an operator could turn it off. Each document the `OP_MSG` parser reads goes through the validator's **default mode**, which the source describes as fast structural consistency checks: - **Rejected with `InvalidBSON`:** lengths that disagree with the data, an unrecognised type byte, a boolean byte that is neither 0 nor 1, a missing terminator. - **Not checked in this mode:** duplicate field names, invalid UTF-8 in strings, deprecated types such as Symbol, a subtype 4 value that is not 16 bytes. Those belong to the full mode, reached by `validate` with `checkBSONConformance: true`. So "the server validates BSON" means "the structure is sound", not "the document conforms".

  • How does an unacknowledged write work over OP_MSG?
    The client sets the `moreToCome` flag on the request and uses `w=0`, and the server sends no reply. Errors such as a duplicate key are swallowed. If the server finds it is no longer primary, it closes the connection, and the client learns that on its next use of the socket.
  • Why have a kind 1 section at all, when the command document could hold an array?
    A BSON array is a document with numeric string keys, so every element pays for a key. A sequence places documents end to end with no keys, and each one can be up to the document limit while the message as a whole stays under the larger message limit. A single body document could not hold that much.
  • If the server validates all incoming BSON in 9.0, why would corrupt data still surface later?
    The incoming check is structural. A document with duplicate names or invalid UTF-8 passes it, and data written before an upgrade was checked under the earlier setting. A stricter sweep of stored data is a separate step, using `validate` with `checkBSONConformance: true`, which reports issues as warnings.

  • messageLength counts only the bytes after the 16-byte header.
  • The 16 MiB document limit is part of the BSON specification.
  • maxMessageSizeBytes and maxBsonObjectSize are the same limit under two names.
  • A kind 1 section's size includes the section's kind byte.
  • Setting net.wireObjectCheck to false turns off BSON validation in MongoDB 9.0.
  • MongoDB's incoming BSON validation rejects duplicate field names and invalid UTF-8.

Assumes MongoDB 9.0: net.wireObjectCheck is deprecated and validation of incoming BSON always runs.