Is the class generator inheriting Sequence thread safe in Keras/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
In Keras, subclassing Sequence is safer than using a plain Python generator when data loading happens with workers, but it is not a magic thread-safety shield for every custom implementation. Sequence gives Keras predictable indexing and epoch semantics, while your own code still has to avoid unsafe shared mutable state.
What Sequence Actually Guarantees
keras.utils.Sequence is designed for indexed batch access. Keras can ask for batch 0, batch 1, and so on, and it knows how many batches exist because the class provides both __len__ and __getitem__.
Minimal example:
That indexed design is why Sequence works better with multiprocessing and avoids some duplication issues seen with naive generators.
Safer Than a Plain Generator Does Not Mean Fully Safe
The important distinction is:
- Keras can schedule
Sequencebatches more safely than a plain generator - your
__getitem__implementation can still be unsafe if it mutates shared state badly
For example, this is risky:
If multiple workers touch shared mutable state like counter, the behavior becomes hard to reason about.
Keep __getitem__ Stateless or Predictable
The safest pattern is for __getitem__ to compute a batch entirely from the requested index and immutable data sources.
Good traits:
- batch contents depend on
index - no global counters
- no random mutation of shared lists
- no side effects that another worker can race with
If you need shuffling, update the index mapping in on_epoch_end rather than inside __getitem__.
This is much easier to keep safe than a batcher that mutates state during every fetch.
Watch External Libraries Too
Even if your Sequence logic is clean, the code it calls may not be thread-safe. Common examples include:
- image decoders with shared caches
- global random state
- file handles reused across workers
- database clients not intended for concurrent access
Sequence does not protect you from those issues. It only gives Keras a safer contract for requesting batches.
Sequence Versus Newer Input Pipelines
For new TensorFlow-heavy projects, tf.data is often a better long-term input pipeline choice because it gives clearer control over parallelism, prefetching, and graph-friendly transformations. Sequence still makes sense when you need Python-side logic, existing NumPy data, or a quick integration with model.fit.
Use Sequence when:
- your loader is naturally batch-indexed
- Python-side preprocessing is acceptable
- you want something safer than a bare generator
Use tf.data when:
- the input pipeline is performance critical
- TensorFlow-native transformations are possible
- you need more control over pipeline execution
Common Pitfalls
The biggest mistake is assuming Sequence makes non-thread-safe code safe automatically. It does not.
Another issue is mutating shared counters, file pointers, or caches inside __getitem__. Indexed fetching works best when the method is close to pure.
A third problem is debugging duplicate or inconsistent batches without checking custom shuffling logic in on_epoch_end.
Summary
- '
Sequenceis safer than a plain generator for Keras worker-based loading.' - Its main advantage is predictable indexed batch retrieval.
- Your own
__getitem__logic still needs to avoid unsafe shared mutable state. - Keep batch generation index-driven and side-effect-light.
- Consider
tf.datawhen you need a more scalable or TensorFlow-native pipeline.
Related reading
- Is the Keras implementation of dropout correct?
- Is the L1 regularization in Keras/Tensorflow really L1-regularization?
- Is the L1 regularization in Keras/Tensorflow really L1-regularization?
- Is there a built-in KL divergence loss function in TensorFlow?
- Is the lock statement reentrant in C?
- Is the lock statement reentrant in C?
- Is there a keras method to split data?
- Is there a momentum option for Adam optimizer in Keras?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free 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.