AWS Builder Center
Your Iceberg Table Is Already an Offline RL Training Set

Your Iceberg Table Is Already an Offline RL Training Set

Train offline RL policies on time-series data straight from an Apache Iceberg table on S3 — no ETL-to-training-format step, using Ray RLlib.

Your Iceberg Table Is Already an Offline RL Training Set

Most machine-learning tutorials start with "first, export your data to a training format." I want to make the case that for a large class of time-series problems, that step is wasted motion — and that an  Apache Iceberg  table sitting on Amazon S3 is already a training-ready feature store you can point a distributed reinforcement-learning trainer at directly.
I've been working through this on a real control problem — optimizing plunger lift on gas wells — and the pattern turned out to be clean enough that it's worth writing down. The short version: offline RL consumes a static dataset of  (state, action, reward, next_state)  transitions. That's just a time-series table with a few derived columns. If your operating history already lives in Iceberg, you have a training set. No copy, no export, no "materialize a training CSV" job.
Here's how the pieces fit together.

Why offline RL and time-series are a natural match

Offline (or "batch") reinforcement learning learns a policy from a fixed dataset of past decisions and their outcomes —  without ever interacting with a live environment  during training. That constraint is usually framed as a limitation. For operational time series, it's the whole point: you can't A/B test pressure setpoints on a physical gas well, but you have years of recorded cycles where different setpoints produced different production rates. The historical operating record is the training set.
Concretely, the problem I'll use throughout: plunger lift is an artificial-lift method where liquid accumulates in a gas wellbore and periodically has to be unloaded by opening the well and letting a plunger travel up. The control question is what pressure setpoint should trigger opening the well, given how much liquid has accumulated? Each plunger-lift cycle is one transition:
RL concept
Physical meaning
Table column
Observation (state)
Liquid slug size
 observation 
Action
Pressure open-trigger setpoint
 actions 
Reward
Average gas rate produced
 AvgGasRate 
Next observation
Slug size on the following cycle
 next_obs 
A little more detail on the two variables that carry the whole problem:
  • The state is the liquid slug size — how much liquid has accumulated in the wellbore, in cubic inches, going into a cycle. It's a single scalar, so the observation space is one-dimensional. This is the thing the policy gets to see before it decides. In the data it clusters in roughly the 4–8 in³ range, even though the physically-possible range is wider.
  • The action is the pressure open-trigger setpoint — the casing-minus-flowline pressure (in psi) at which the controller opens the well to unload the slug. Also a single scalar, so the action space is one-dimensional too. Open too early and you vent gas without lifting much liquid; open too late and the slug gets heavy enough to stall the plunger. In the historical record the operators' setpoints cluster in the 1.0–1.6 band.
So the learned policy is a function  π(action | observation)  — given the slug size, what pressure setpoint would have produced a higher average gas rate than the strategy the operators actually ran? Every row is a  (state, action, reward, next_state)  tuple. That's exactly the shape offline RL wants.

Why Iceberg specifically

Plenty of formats can store time series. Iceberg earns its place here because of what it gives an ML workload that a pile of Parquet files or a Hive table doesn't:
What the workload needs
What Iceberg provides
"Train on the data as of last Tuesday"
 Snapshots 
— every write produces an immutable snapshot you can scan at any point in time
Reproducible training runs
A snapshot ID pins the exact set of files — the same run is re-runnable months later
New sensors get added over time
 Schema evolution 
without rewriting history
Reads by many parallel workers
Table metadata lists the concrete Parquet files, so N workers split the list and read in parallel
Read only the columns/rows you need
 Column projection + predicate pushdown 
at the Parquet level
No lock-in
Open format on open storage, readable by Spark, Trino,
 Athena 
, DuckDB, Ray, PyIceberg
The snapshot mechanism is the one that matters most for ML governance. "Retrain the model on the data as of the incident date" becomes a one-line change and is bit-for-bit reproducible — which is exactly the kind of lineage guarantee auditors ask for and most ad-hoc training pipelines can't give.

The pipeline, in four stages

I'm using  Ray RLlib's offline-data API  as the trainer. The whole flow is four stages, and understanding it once explains the entire pipeline.

Stage A — Resolve the snapshot to a file list

This is the crux of the value proposition.  PyIceberg  reads the table metadata and hands back the exact set of Parquet files behind the current snapshot — without reading any data.
from pyiceberg.catalog import load_catalog

catalog = load_catalog("glue", **{"type": "glue"})
table = catalog.load_table("upstream.plunger_lift_cycles_ml_train_iceberg")

latest_snapshot = table.current_snapshot() # immutable, reproducible pin
data_files = table.scan().plan_files() # metadata-only file planning
s3_paths = [df.file.file_path for df in data_files]
 table.scan().plan_files()  touches metadata only. It returns the concrete  s3://…/file_0001.parquet  paths, and we hand those straight to the trainer. Want last month's data instead? Scan an older snapshot — the file list differs and the run is exactly reproducible. Here I'm using the  AWS Glue Data Catalog  as the Iceberg catalog, so the table is also queryable from Athena and anything else that speaks Glue.

Stage B — Declare the data source to RLlib

 .offline_data(...)  tells RLlib to build a  Ray Data  pipeline over those Parquet files:
.offline_data(
input_=s3_paths,
input_read_method="read_parquet",
input_read_method_kwargs={
"columns": ["observation", "actions", "AvgGasRate", "next_obs", "LiquidProductionRate"],
"filter": ~(
pa.dataset.field("observation").is_null() |
pa.dataset.field("actions").is_null() |
pa.dataset.field("AvgGasRate").is_null() |
pa.dataset.field("next_obs").is_null()
),
},
input_read_schema={
Columns.OBS: "observation",
Columns.ACTIONS: "actions",
Columns.REWARDS: "AvgGasRate",
Columns.NEXT_OBS: "next_obs",
Columns.TERMINATEDS: "AvgGasRate",
},
)
Two lines here are pure Iceberg/Parquet leverage:
  • Column projection ( columns=[...] ): the table has ~20 columns; the trainer reads five. Unread columns cost zero I/O.
  • Predicate pushdown ( filter=... ): raw historian data has  NaN / NaT  gaps. Rows with nulls in a required column get dropped at the Parquet layer, before a single byte reaches the learner. That filter is what makes messy operational data trainable without a separate cleaning job.
 input_read_schema  is the adapter between the domain's column names and RLlib's internal  Columns.*  contract. Mapping  TERMINATEDS  to  AvgGasRate  is a modeling choice — each cycle is treated as its own single-step transition rather than part of a long episode.

Stage C — Transform in parallel, on the fly

map_batches_kwargs={"concurrency": 4, "num_cpus": 1},
iter_batches_kwargs={"prefetch_batches": 4, "local_shuffle_buffer_size": 1000},
dataset_num_iters_per_learner=3,
Ray Data spins up workers that pull Parquet batches, reshape them into RLlib's sample structures, and stream them to the learners — never fully materialized in memory. This is how the same code goes from a few files to thousands: the file list from Stage A is simply split across more workers. The local shuffle buffer decorrelates samples, which matters for training stability.

Stage D — Train, checkpoint, stop

The algorithm is wrapped in a  Ray Tune   Tuner , which handles checkpointing, metrics, and optional hyperparameter search. Which brings us to the algorithm choice — and the one problem that dominates offline RL.

The hard part: out-of-distribution actions

Here's the failure mode that makes offline RL its own discipline. A naive Q-learning agent trained on a fixed dataset will discover that its learned Q-function assigns spuriously high value to actions that never appear in the data — because there's no data to contradict those estimates. It then confidently recommends those unseen actions. On a physical gas well, acting on an out-of-distribution (OOD) pressure setpoint isn't a rounding error; it's a bad operational decision.
 Conservative Q-Learning (CQL)  is built to counter exactly this. It adds a penalty that pushes down Q-values for OOD actions, pulling the policy back toward what the data actually supports. It's the right default for anything where a wrong recommendation has real-world cost. On top of CQL, I layer three more defenses.

Defense 1 — Constrain the spaces to the data

RLlib needs an environment to know the shape and bounds of actions and observations — but for offline training it never calls  step()  or  reset() , because nothing is simulated. So the environment is a space declaration and nothing else:
class PlungerLiftEnv(gym.Env):
def __init__(self, config=None):
self.action_space = Box(low=0.8, high=1.8, shape=(1,)) # narrowed from [0.5, 2.0]
self.observation_space = Box(low=0.0, high=12.0, shape=(1,)) # narrowed from [0, 15]
The bounds are deliberately tightened from the physically-possible range down to the range actually observed in the data. The action  Box  narrows to  [0.8, 1.8]  — a snug collar around the  1.0–1.6  band the operators' pressure setpoints actually lived in — and the observation  Box  narrows to  [0.0, 12.0] , bracketing the slug sizes that show up in the record. Narrowing the action space mechanically prevents the policy from even representing a pressure setpoint far outside what the well has ever been run at. It's a crude guardrail, but a free one.

Defense 2 — CQL conservatism and a BC warm-start

config = (
CQLConfig()
.environment(env="PlungerLiftEnv")
.learners(num_learners=2, num_cpus_per_learner=2)
.training(
train_batch_size_per_learner=2**12, # 4096
gamma=0.9,
lr=None, # CQL/SAC set actor/critic/alpha LRs individually
bc_iters=50000, # behavioral-cloning warm-start
)
.offline_data(...) # Stages B & C
.callbacks(create_stop_after_n_iters_callback(max_iters=5001))
)
Two things worth calling out:
  •  lr=None  is intentional, not a bug. CQL is built on  Soft Actor-Critic , which has three separate optimizers — actor, critic, and the temperature parameter α. You set  actor_lr ,  critic_lr , and  alpha_lr  individually and leave the global  lr  unset.
  •  bc_iters=50000  warm-starts the policy with pure  behavioral cloning  before CQL's Q-learning kicks in. Starting close to the data distribution prevents early divergence — a third OOD defense, for free.
Notice  num_learners=2 : training is distributed by config, not by code. The same knob scales this from a laptop to a GPU cluster, and nothing else in the script changes — because the read path is just a file list that splits across workers.

Closing the loop: the same table evaluates the policy

Since there's no simulator, you evaluate by inspection — and this is where the OOD story becomes something you can literally see.
Checkpoint every 10 iterations. Then, for each checkpoint, reload the policy, run it over a grid of observations, and record the action it would recommend. That traces how the policy evolves across training. Now query the same Iceberg table for the actual historical  (observation, action)  pairs and overlay them as a scatter plot underneath the learned policy curves.
Plot of Learned Policy with Data Support

If the learned policy stays inside the cloud of what the data supports, the conservatism machinery is working. If it wanders off into empty regions, you can see that too — before anyone acts on it. The same snapshot supplies both the training data and the ground-truth evaluation overlay, with zero data duplication.

The takeaways

If you have operational time series in Iceberg, this pattern is worth a look:
  1. Your historian is already your training set. No export or reformatting to train an RL policy — RLlib reads the table's Parquet files directly.
  1. Reproducibility is built in. A snapshot ID pins the exact files a model trained on. Retraining "as of the incident date" is one line and bit-for-bit reproducible.
  1. You pay only for the data you use. Column projection and predicate pushdown mean the job reads 5 of 20 columns and skips null rows before I/O — real savings at scale.
  1. It scales without rewrites. Go from a laptop to a multi-learner cluster by changing  num_learners ; the file-list read parallelizes naturally.
  1. Offline RL here is safe by construction. Training never touches the physical asset, and CQL + space constraints + a BC warm-start keep recommendations inside the envelope the data supports.
A couple of honest caveats. This is a research pattern, not a productized system — getting to a policy you'd actually deploy takes a real CQL tuning campaign and domain validation with the engineers who own the asset. And the "cycle = single-step transition" framing is a modeling choice, not a law of nature. But the core idea holds up: for time-series control problems, the gap between "we have the data" and "we have a training set" is a lot smaller than the usual ML tooling makes it look. Iceberg closes most of it.
If you're working on something similar, I'd love to hear how you're framing the reward — that's where most of the real modeling work lives.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article