One weather field for thousands of cities: batch reading and decoding

An original binary laboratory groups city requests by field, reads each block once and separates decoder calls, source bytes and missing values.

A conceptual illustration of one atmospheric field passing over many settlements.

When several cities use the same weather field, it is easy to organise the work around a city: open the source, decode the field, take one value and move to the next city. The result can be correct while the same block of bytes passes through the decoder many times. Deduplicating coordinates removes only some repetition. Different nodes can also belong to a single field that can be processed together.

After asking “how many distinct points do we need?”, another question therefore follows: what physical unit of reading and decoding serves those points? We will test it with our own binary format, SYN1. The experiment contains six fictional cities, two fields and eight positions in each. It is an executable model of how to organise the work, not a GRIB decoder or a throughput test for thousands of cities.

A field, a block and a value have different sizes

A city needs a particular value: temperature at a given forecast horizon, for example. The source may provide a wider field from which the required position still has to be selected. If the decoder unpacks the entire block every time, a call for one node does not mean processing one number.

In our exercise, one field occupies one block. This is a deliberately simple contract. Actual GRIB2 has separate sections for grid definition, product definition, data representation, bitmap and data. The boundaries of a transport object, message and required field must come from the format and metadata, not from guessing based on the city count.

We will separate four counters immediately: city/field requests, distinct position/field pairs, blocks read and decoder calls. We will also count bytes received and values decoded. This reveals repeated expensive operations even when the output values are correct.

HTTP requests do not automatically belong in that list. Our source is a dictionary of immutable bytes in memory. Its read is an ordinary function call. A future transport adapter would need its own network counters: the block count does not determine the number of connections, retries or responses.

A small format with literal expectations

The SYN1 header occupies eight bytes. Signed 16-bit values follow it, in position order from zero to the final position:

Part Size Meaning in the exercise
Signature 4 bytes SYN1
Field code 1 byte 1 for temperature, 2 for humidity
Horizon 1 byte Whole hours, from 0 to 255
Position count 2 bytes 8 in the main fixture
Values 2 bytes per position Signed integers; -32768 means missing

All numbers use big-endian byte order. Python specifies this explicitly with the > prefix in struct. The machine’s native byte order does not become a hidden part of the contract. The header is described as >4sBBH; values are a sequence of h with the same prefix.

The temperature field uses tenths of a degree Celsius; humidity uses percent. A raw temperature value of 100, for example, means 10 °C; this article retains the raw integers. Zero is valid. The reserved -32768 becomes None, so a missing value cannot silently become a temperature of zero.

The bytes are literal hex strings in fixtures.json. Expected unpacked arrays appear alongside them; a separate expected.json contains expectations for cities and counters. The example does not generate its test bytes with the same packer whose correctness it then supposedly proves. A negative number in the first position additionally checks the sign and byte order.

Group by the complete field context

Cities a and b request position 1, c and d request position 3, and e and f request position 7. Each needs temperature and humidity at a three-hour horizon. That gives twelve city results, six distinct position/field pairs and only two blocks.

The grouping key contains the source, model, run, source revision, grid, grid revision, variable, horizon and expected field size. The position index stays in the city’s request. Including it in the physical block key would make different nodes cause repeated decoding again.

Removing the run or revision from that key is dangerous, however: a shared variable name does not make two releases identical. In the test, one city’s requests for two revisions remain two separate results and require two reads. The code does not merge them under the short field name.

The batch’s main loop is simple:

for field, selected in sorted(groups.items()):
    values = decode(source.read(field), field, source.counters)
    for request in selected:
        result.append(Value(request.city_id, field, request.index, values[request.index]))
    del values

Results retain the city, complete key, index and value. They are sorted at the end, so reordering input requests does not change the answer. Decoding is shared; city identity remains. A repeated request by the same city for the same field is rejected so that ambiguity cannot disappear while building a dictionary.

What actually changed when we ran it

We executed two variants over the same bytes. The naive variant reads and unpacks a field for each city. The batch variant does this once for each complete field key, then distributes the selected values.

Observed counter Naive traversal Batch traversal
Calls to the in-memory source 12 2
Bytes received from that source 288 48
Decoder calls 12 2
Total values decoded 96 16
Largest individual decoded field 8 positions 8 positions
City/field results returned 12 12

One block contains 24 bytes: eight header bytes and sixteen value bytes. The byte counter increases after actually receiving such a block from memory. It is neither the network traffic size nor the process’s total memory usage.

Both variants returned identical results. Cities at position 3 received temperature 0; those at position 7 received None. Adding another hundred city requests for the already required temperature field increased the result count but retained two reads and two decodes. That separate test checks the reuse rule, not a load limit.

The experiment does not measure time, CPU or a speedup factor. Fewer calls are the confirmed result here. How much that changes a real cycle’s duration depends on the decoder, transport layer, repetition rate and subsequent processing.

A batch needs bounds and an honest failure

All requests are checked before the first read: identities, supported variables, horizon, field size and integer indices within its bounds. Boolean True is not accepted as an index. Even an error in the last request stops the plan before accessing the source.

The decoder separately checks the signature, variable code, horizon, position count and exact block length. A truncated tail and an extra byte are equally unacceptable. The teaching limit of 4096 positions is checked before unpacking values. It promises no whole-process limit: input bytes already live in the dictionary, and output results also occupy memory.

This decoder fully unpacks one field. The batch loop releases its reference to that array after distribution, but the decoder itself temporarily creates several Python objects. The “largest field” counter describes position count, not measured peak RSS. Large fields require a separate decision: selective decoding, an iterator, a bounded queue or another data structure.

If the second block is corrupt, the function returns no partial result collection. The first read and decode have already occurred, and their counters remain. There is no external write here; this example implements no publication protocol, recovery process or transaction guarantee.

Where the GRIB analogy ends

SYN1 supports no compression, geographical grid scanning, temporal aggregates, ensembles or arbitrary units. Its header checks the variable, horizon and size; matching the source, run and grid to the bytes is entrusted to the input fixture. There is no cryptographic provenance check.

Likewise, the reserved integer for missing data is only our exercise’s rule. An official ecCodes example shows checking the bitmap while iterating over values. Carrying our sentinel into GRIB without analysing the format would be a mistake. A separate example demonstrates multi-field GRIB2 messages, so “one block equals one field” is not a universal rule either.

An actual GRIB execution was not run in this laboratory. Making that transition requires permitted real fixtures, metadata and missing-value checks, comparison with an independent decoder, and our own time and memory measurements. Organising work into batches replaces none of these checks.

Scope of the local check

The local check used the Python standard library.

Twenty-six test methods ran under Python 3.12.14: literal bytes and results, different revisions and horizons, reordering, missing values, invalid indices, damaged headers and second-block failures. Another separate call to the batch function reads the fields again: there is no durable cache between executions.

The practical decision after this experiment is to place counters at the actual boundaries of the work. Count required values, physically read blocks, decodes and retained results separately. That reveals where one shared field already serves many cities and where the system still repeats the same operation.

  1. Weather An optimization that failed validation: evaluating speed across the whole path
  2. Weather When to defer an import: CPU, memory and time budgets alongside a live website
  3. Weather Selecting fields from a weather file: the index, byte ranges and source version
  4. Weather 77 thousand cities: how many distinct forecast points need processing