HDF5

Also known as: Hierarchical Data Format version 5 · HDF

On this page 7

HDF5, short for Hierarchical Data Format version 5, is a self-describing binary file format and accompanying C library that stores large numerical arrays and their metadata inside a single file organized like a file system of groups and datasets. Among data formats in the field of data engineering and scientific computing, it is the long-established choice for dense multidimensional arrays produced by simulations, instruments and machine learning pipelines.

The format was developed at the National Center for Supercomputing Applications and is now maintained by The HDF Group. Unlike row-oriented text formats such as CSV or JSON, HDF5 offers random access to slices of arrays that can be far larger than memory, together with chunking, compression and typed attributes in one container.

How HDF5 organizes data inside one file

An HDF5 file is a rooted, directed graph of objects that behaves much like a directory tree. The root group, written /, contains groups (analogous to folders) and datasets (analogous to files holding typed arrays). Any object can carry attributes, which are small named values used for units, calibration constants or provenance.

Each dataset has a datatype and a dataspace. The datatype defines how one element is encoded, from 8-bit integers to IEEE floating-point numbers, fixed or variable-length strings and compound records. The dataspace defines the rank and dimensions, which may be fixed or extendible up to an unlimited maximum when chunked storage is used.

The following table lists the core object types and the role each plays in a typical file.

ObjectPurposeTypical content
GroupContainer that holds links to other objectsExperiment runs, sensor channels, model layers
DatasetTyped multidimensional arrayImages, time series, simulation grids, weights
AttributeSmall metadata value attached to an objectUnits, timestamps, software version
DatatypeElement encoding, can be stored and sharedFloat64, int16, compound record, string
DataspaceShape and maximum shape of an array1024 x 1024 x 360, or unlimited first axis
LinkNamed path to an object, hard, soft or externalPointer to a dataset in another file
Core HDF5 object types

Storage layouts, chunking and compression

HDF5 separates the logical array from its physical layout on disk. Contiguous storage writes the array as one block and suits small datasets read in full. Chunked storage splits the array into equally sized tiles indexed by a B-tree or newer index structures, which enables partial reads, extension and compression. Compact storage places very small data directly in the object header.

Compression and other transformations run through the filter pipeline, which processes each chunk independently. Built-in filters include gzip (deflate), shuffle and Fletcher32 checksums, while registered plugins add LZ4, Zstandard, Blosc and lossy codecs such as ZFP or SZ for floating-point science data.

Choosing a layout is a trade-off between access speed, file size and flexibility, as the table summarizes.

LayoutStrengthLimitationBest fit
ContiguousFast sequential full readsNo compression, no resizingSmall fixed arrays read whole
ChunkedPartial I/O, compression, extendible shapeOverhead if chunks are badly sizedLarge arrays read by slice
CompactNo separate allocationLimited to about 64 KBTiny lookup tables
VirtualCombines datasets across filesComplex to manage and debugDetector data split into many files
Dataset layouts compared

Chunk shape matters more than any other tuning decision. Chunks should match the dominant access pattern, and a common guideline is about 10 KB to 1 MB per chunk. Chunks that are too small inflate the index and metadata, while chunks that are too large force the library to decompress far more data than a query needs.

HDF5 compared with neighboring data formats

HDF5 occupies the niche of array-oriented, single-file scientific storage, which differs from columnar analytics formats and from text interchange formats. NetCDF-4 is built on top of HDF5 and adds stricter conventions for geoscience variables, while Zarr stores the same chunked-array concept as separate objects suited to cloud storage.

FormatData modelStorage unitTypical domain
HDF5Hierarchical typed arraysOne binary fileSimulation, instruments, deep learning
NetCDF-4Variables and dimensions on HDF5One binary fileClimate, oceanography, weather
ZarrChunked arrays with JSON metadataMany objects or filesCloud-native array analytics
ParquetColumnar tablesFiles with row groupsData lakes, SQL analytics
CSVFlat text rowsText fileSimple tabular interchange
HDF5 and related formats

The practical boundary is the shape of the data. Tabular records with many columns and filtering by value belong in Parquet or ORC, whereas dense numerical grids read by spatial or temporal windows belong in HDF5, NetCDF or Zarr.

Working with HDF5 in practice

Most users access HDF5 through bindings rather than the C API. In Python, h5py exposes datasets as NumPy-like objects, and PyTables adds indexed tables, while MATLAB uses HDF5 as the basis of its version 7.3 MAT-files. Command-line tools such as h5dump, h5ls and h5repack inspect and reorganize files without custom code.

Parallel workloads on supercomputers use Parallel HDF5, which relies on MPI-IO so that many processes write disjoint regions of one shared file. The single-writer multiple-reader (SWMR) mode lets one process append to a file while others read it, which supports live monitoring of instrument streams.

The decision table below maps common situations to a sensible configuration.

SituationRecommended choiceReason
Time series appended continuouslyChunked with unlimited axisAllows growth without rewriting the file
Image stack read frame by frameOne frame per chunkEach read touches exactly one chunk
Archive where size dominatesShuffle plus gzip or ZstandardShuffle improves compression of numbers
Many cluster processes writingParallel HDF5 with collective I/OCoordinates writes to one shared file
Data read from object storageConsider Zarr or cloud-optimized HDF5Avoids many small ranged requests
Configuration choices by situation

Limitations and common pitfalls

HDF5 is powerful but carries well-known operational risks. Because many objects share internal metadata structures, an interrupted write can leave a file corrupted and unreadable, so robust pipelines write to a temporary file and rename it after closing. Deleting a dataset does not shrink the file; the space is reclaimed only by rewriting with h5repack or by enabling file-space management strategies.

  • Concurrency is limited: the default library build serializes calls with a global lock, so threads do not gain parallel I/O.
  • Cloud access is awkward: reading scattered chunks over HTTP issues many small requests unless the file is consolidated or paged.
  • Filter plugins must be available to readers, otherwise a dataset compressed with a custom codec cannot be opened.
  • Version compatibility needs care: files written with newer features may not open in old library releases.

A frequent misconception is that HDF5 is a database. It provides no query language, transactions or indexes by value in the core library, so applications that filter records by content usually pair it with an external index or choose a tabular format.

In plain words

HDF5 is a way to keep a huge amount of numbers in one tidy file. Inside, it looks like a set of folders. Each folder can hold big grids of numbers. Labels explain them, such as units or dates.

Its main advantage is simple. A program can read just the piece it needs. It is like opening one page of a giant atlas instead of carrying the whole book. That is why scientists use it for data too large to load at once.

A real-world example

A synchrotron beamline records a detector producing 4,000 frames per second, each frame 2,048 by 2,048 pixels stored as 16-bit integers. The acquisition software writes every scan to an HDF5 file with a dataset of shape frames by rows by columns, an unlimited first axis and one frame per chunk, compressed with a Blosc LZ4 filter. Attributes record the beam energy, exposure time and detector distance.

During the experiment, SWMR mode lets an analysis process read new frames while acquisition continues, so scientists see reconstructed images within seconds. After the run, the compressed files take roughly one third of the raw size, and researchers later open them in Python with h5py, slicing a few hundred frames at a time without loading the multi-terabyte scan into memory.