How to handle large amouts of data in tensorflow?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
When your dataset no longer fits in memory, the way you feed data into your model becomes the bottleneck, not the model itself. TensorFlow provides a complete data pipeline framework built around tf.data.Dataset that lets you stream, transform, and prefetch data so the GPU never sits idle waiting for the next batch. This article covers five techniques for efficiently handling large datasets: the tf.data API, TFRecord format, parallel I/O with interleave and prefetch, CSV ingestion, and distributed training with MirroredStrategy.
tf.data.Dataset Pipeline
The tf.data.Dataset API is the foundation of all large-scale data handling in TensorFlow. Instead of loading everything into a NumPy array, you build a lazy pipeline that reads data on demand.
The key idea is that map, batch, and prefetch are chained into a pipeline that overlaps data loading with model training. The AUTOTUNE flag lets TensorFlow dynamically tune the number of parallel threads and the prefetch buffer size based on available resources.
TFRecord Format
TFRecord is TensorFlow's native binary format for storing serialized protocol buffers. It is designed for sequential reads, which makes it significantly faster than reading thousands of individual files from disk.
For very large datasets, split the data across multiple TFRecord files (called sharding). This enables parallel reads and makes it easier to distribute data across machines.
Interleave and Prefetch for Parallel I/O
When data is spread across many files, interleave reads from multiple files simultaneously. Combined with prefetch, this keeps the training loop fed with data even when individual file reads are slow.
The cycle_length parameter controls how many files are open at the same time. Setting deterministic=False allows TensorFlow to yield whichever record is ready first, which improves throughput when file read times vary. The prefetch at the end ensures that the next batch is already in memory while the current batch is being processed by the GPU.
CsvDataset for Tabular Data
For tabular data stored in CSV files, tf.data.experimental.CsvDataset reads rows directly into tensors without loading the entire file into a pandas DataFrame first.
You can also pass a list of filenames to read from multiple CSV files. This is useful when data arrives in daily or hourly partitions. For more complex CSV processing (missing values, string encoding), consider using tf.data.experimental.make_csv_dataset, which handles column naming and batching automatically.
Distributed Training with MirroredStrategy
When a single GPU cannot process data fast enough, tf.distribute.MirroredStrategy replicates your model across multiple GPUs on the same machine. Each GPU processes a slice of the batch in parallel, and gradients are synchronized automatically.
The critical detail is that everything inside strategy.scope() is replicated. The dataset is automatically sharded across GPUs. Scale the global batch size proportionally so each GPU still processes the same per-replica batch size. For multi-machine training, switch to tf.distribute.MultiWorkerMirroredStrategy.
Common Pitfalls
- Loading the entire dataset into memory with NumPy before creating a Dataset: This defeats the purpose of
tf.data. Uselist_files,TFRecordDataset, orCsvDatasetto stream data from disk. - Forgetting to call prefetch at the end of the pipeline: Without prefetch, the GPU waits for data loading to finish after each batch. A single
.prefetch(tf.data.AUTOTUNE)at the end of your pipeline is the simplest performance win. - Setting shuffle buffer_size too small: A buffer of 100 on a dataset of 1 million records produces nearly sequential batches, which can hurt model convergence. Set the buffer to at least several thousand, or use pre-shuffled TFRecord shards.
- Not scaling the batch size with MirroredStrategy: If you use the same global batch size across 4 GPUs, each GPU only processes one quarter of a batch, wasting compute. Multiply the base batch size by the number of replicas.
- Writing a single massive TFRecord file: One large file cannot be read in parallel. Shard your data into files of 100 to 200 MB each so
interleavecan read from multiple files simultaneously.
Summary
tf.data.Datasetis the core abstraction for streaming data through a lazy, chainable pipeline of map, batch, and prefetch operations.- TFRecord is TensorFlow's optimized binary format for sequential reads; shard large datasets into multiple files for parallel I/O.
interleave+prefetchoverlap file reading with GPU training, eliminating I/O bottlenecks in multi-file pipelines.CsvDatasetreads tabular data directly into tensors without loading entire files into memory.MirroredStrategydistributes training across multiple GPUs with automatic gradient synchronization; always scale the global batch size by the number of replicas.
Related reading
- How to handle large amouts of data in tensorflow?
- How to handle non-determinism when training on a GPU?
- How to handle non-determinism when training on a GPU?
- How to handle RGB images in Keras
- How to handle variable sized input in CNN with Keras?
- How to have predictions AND labels returned with tf.estimator either with predict or eval method?
- How to handle log0 when using cross entropy
- How to handle missing NaNs for machine learning in python

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.