Home / Insights / AI and Machine Learning
AI and Machine Learning
Python Data Pipelines for AI Features: From Notebooks to Scheduled Production Jobs
Most AI features start as a notebook that works on someone’s laptop. Shipping the feature means turning that notebook into scheduled jobs that rerun safely, fail loudly and can be handed to another engineer. This is the path we use.
Key takeaways
- A notebook proves an idea; a pipeline is a set of small, tested, idempotent Python steps that read fixed inputs and write versioned outputs.
- Choose orchestration by need: cron or a managed scheduler for a handful of jobs, Airflow or Dagster when you have dependencies, backfills and several owners.
- Idempotency is the single most important property. Every step should be safe to rerun for the same date or partition without duplicating data.
- Validate data before it reaches a model or an embedding index. Schema problems should stop the run; gradual drift should raise an alert.
- Budget for operations from day one: alerting, run history, data lineage and an owner for each job. Most pipeline cost is maintenance, not the first build.
On this page
- Why does notebook code break in production?
- How should you restructure notebook code?
- Which orchestration option fits your stage?
- What engineering rules keep pipelines safe to rerun?
- How do you test pipelines and validate data?
- What does it cost to operate pipelines?
- Checklist: is your pipeline production-ready?
- Frequently asked questions
- Sources and methodology
Product teams adding AI features, such as recommendations, document classification, retrieval for an assistant or demand forecasts, quickly discover that the model is the easy part. The hard part is the data work around it: pulling records from operational systems, cleaning them, computing features or embeddings, and refreshing all of that on a schedule without anyone watching.
This article is for CTOs, engineering leads and product owners who have a working notebook or prototype and need to decide how to run it in production. It covers how to restructure notebook code, how to choose an orchestrator, the engineering rules that keep jobs safe to rerun, how to test and validate data, and what operating the pipelines will cost. It closes with a checklist you can use in planning or vendor reviews.
Why does notebook code break in production?
Notebooks are excellent for exploration. They let a data scientist try ideas quickly, inspect intermediate results and plot as they go. The same properties make them fragile as production code: cells run out of order, state lives in memory, file paths point at a laptop, and “the latest data” means whatever was downloaded last Tuesday.
Google Cloud’s MLOps architecture guide describes this starting point as level 0: a manual, interactive, notebook-driven process in which a trained model is handed over to engineers, releases are infrequent, and predictions are not logged to detect degradation. It also names a specific risk of that hand-off, training-serving skew, where features computed for training differ from those computed at prediction time (Google Cloud: MLOps continuous delivery and automation pipelines).
The longer-term cost is maintenance. The NeurIPS paper Hidden Technical Debt in Machine Learning Systems argues that ML systems readily accumulate massive ongoing maintenance costs, and lists data dependencies, entanglement, configuration issues and changes in the external world among the causes (Sculley et al., NeurIPS 2015). Pipelines are where most of that debt lives.
Symptoms that you need a real pipeline
- The feature depends on one person rerunning a notebook every week.
- Nobody can say which data a model or embedding index was built from.
- A failed run is discovered by a customer, not by an alert.
- Rerunning a job creates duplicate rows or double-counts events.
- Credentials are pasted into notebook cells.
Action: list every manual step between “new data arrives” and “the AI feature uses it”. Each manual step is a candidate for automation and a likely source of failure.
How should you restructure notebook code?
The goal is not to delete the notebook. Keep it for exploration, and move the logic that must run every day into a normal Python package that the notebook can import.
A structure that works for most teams
- Extract pure functions: each transformation becomes a function that takes data in and returns data out, with no hidden global state. These are easy to unit test with PyTest.
- Separate I/O from logic: reading from a database or object storage and writing results live in thin adapter functions. The business logic never knows whether it is reading a test fixture or production data.
- Make configuration explicit: dates, partitions, model names and thresholds come from parameters or environment variables, not constants in cells.
- Pin dependencies: lock exact package versions and build a container image so the job runs the same on a laptop, in CI and in production.
- Define steps: group functions into steps with clear inputs and outputs, for example
extract_orders,clean_orders,build_features,score,publish.
Where data should live between steps
Steps should hand data to each other through durable storage, such as a database table, a Parquet file in object storage or a warehouse table, not through local disk or memory. Apache Airflow’s best-practice guide makes the same point for its own tasks: because tasks may run on different machines, you should not store files or configuration on the local filesystem, and should pass only small messages or paths between tasks (Apache Airflow: Best practices). If you are still deciding where analytical and AI data should be stored, our comparison of data lakes, warehouses and lakehouses covers the options.
Action: pick one notebook and refactor it into a package with three to six steps and at least one unit test per step before touching orchestration.
Which orchestration option fits your stage?
An orchestrator runs steps in the right order, on a schedule or trigger, retries failures and keeps a history of runs. The right choice depends on how many jobs you have, how they depend on each other and who operates them.
| Option | Good for | Limits |
|---|---|---|
| Cron or a cloud scheduler triggering a container | One to a few independent jobs; small teams | No dependency graph, weak run history, manual backfills |
| Task queue (for example Celery) inside your app | Event-driven work tied to the product, such as embedding a newly uploaded document | Not designed for date-partitioned batch history or backfills |
| Apache Airflow (self-hosted or managed) | Many scheduled batch jobs with dependencies, retries and several owners | Operational overhead; DAG code needs discipline |
| Dagster | Teams that think in data assets and want lineage and data checks built in | Newer concepts to learn; same need to run and monitor the platform |
| Cloud ML pipelines (vendor managed) | Teams standardised on one cloud’s ML tooling | Tighter vendor coupling; less suited to general data work |
Assets versus tasks
Two mental models dominate. Task-oriented tools such as Airflow describe what to run and in what order. Asset-oriented tools such as Dagster describe what data should exist; Dagster’s documentation defines an asset as a logical unit of data such as a table, dataset or machine learning model, with dependencies forming lineage, and supports partitions for incremental processing and asset checks for data quality (Dagster: Concepts). Either works. Asset thinking tends to suit AI features, because the question people ask is usually “is the embedding index for yesterday’s documents up to date?”
A sensible progression
For example, a 20-person SaaS company adding a recommendation feature might start with two containerised jobs triggered by a managed cloud scheduler, then move to Airflow or Dagster once it has five or more interdependent jobs, backfill requests from analysts and a second team relying on the outputs. Moving later is not wasteful if the code was already structured as testable steps.
Action: count your jobs, their dependencies and their owners. Pick the simplest option that covers the next 12 months, not the next five years.
What engineering rules keep pipelines safe to rerun?
Pipelines fail. Networks drop, source systems change, and someone will ask for last month to be recomputed. The design question is whether a rerun repairs the problem or makes it worse.
Idempotency first
Airflow’s guide compares tasks to database transactions that should never leave incomplete results, recommends upserts rather than plain inserts so reruns do not duplicate rows, and warns never to read “the latest available data” inside a task; instead each run should read a fixed partition tied to its data interval, and avoid using the current time for critical calculations (Apache Airflow: Best practices). Those rules apply to any orchestrator:
- Every run is parameterised by a date or partition key.
- Outputs for a partition are overwritten or upserted as a whole, never appended blindly.
- Side effects such as emails, API calls or index updates are recorded with a key so they are not repeated.
Other rules worth enforcing
- Light module import: keep database calls and heavy computation out of module top level, so the scheduler can parse pipeline definitions quickly. Airflow’s guide calls this out explicitly.
- Secrets in a secrets manager: never in code, notebooks or plain environment files committed to a repository.
- Versioned outputs: write model artefacts and embedding indexes with a version and the input partition, so you can roll back.
- Small steps: a failed step should be cheap to retry. A single four-hour job that fails at hour three is expensive.
- Cost controls: AI steps that call paid model APIs need batching, rate limits and a budget alarm.
Action: for each step, write down what happens if it runs twice for the same partition. If the answer is “duplicates” or “two emails”, fix that before going live.
How do you test pipelines and validate data?
Code tests and data tests catch different failures. You need both.
Code tests
- Unit tests for each transformation function, using small fixture data that includes edge cases: nulls, duplicates, time zones, unexpected categories.
- Pipeline definition tests that load every job definition and fail on import errors. Airflow’s guide recommends treating DAGs as production code, with loader tests and a staging environment parameterised by environment variables.
- Integration tests that run a whole pipeline on a sample partition in CI or staging.
Data validation
Google’s MLOps guide recommends validating data before training and distinguishes two cases: schema skew, such as unexpected, missing or wrongly typed features, which should stop the pipeline for investigation, and value skew, a significant shift in statistical properties, which should trigger retraining or review. In practice:
| Check | Example | On failure |
|---|---|---|
| Schema | Required columns present, types correct | Stop the run and alert |
| Volume | Row count within an expected range for the partition | Stop or warn, depending on severity |
| Freshness | Source updated within the last N hours | Delay and retry, then alert |
| Distribution | Category mix or numeric ranges similar to recent runs | Warn and flag for review or retraining |
| Output quality | Model or retrieval metrics on a fixed evaluation set | Block publishing the new version |
For retrieval features, add checks that documents were chunked and embedded as expected, and that a fixed set of test questions still finds the right sources. For a broader view of versioning and monitoring models, see MLOps for Small Teams.
Action: write the five checks in the table for your most important pipeline and decide, for each, whether it stops the run or only alerts.
What does it cost to operate pipelines?
The first build is visible; the running cost is not. Plan for these recurring items:
- Compute and storage: scheduled containers or orchestrator workers, warehouse queries and object storage. AI steps add model API calls or GPU time.
- Orchestrator operation: upgrades, scaling and backups if self-hosted, or subscription fees if managed.
- On-call and support: someone must respond when a job fails at 3am before a morning report or customer-facing feature depends on it.
- Change management: source systems change schemas. Every upstream change is potential pipeline work.
- Documentation and ownership: each pipeline needs a named owner, a runbook and a description of its consumers. Undeclared consumers are one of the debt sources the NeurIPS paper highlights.
Observability you should have from day one
- Run history with duration and status for every job and partition.
- Alerts on failure and on “did not run”, routed to a channel that someone watches.
- Data freshness indicators visible to the product team.
- Lineage: which inputs produced which model or index version.
- Cost per run for steps that call paid APIs.
At PoliteTech, our Python developers build ETL pipelines, data processing and reporting jobs, and LLM and retrieval integrations, using tools such as pandas, Celery, PostgreSQL, Docker and PyTest; see Hire Python Developers for how those engagements work. We have applied the same approach on AI products such as our clinical operations work for an Australian healthcare client, where referral processing depends on reliable document pipelines. If you are hiring for this work, our guide Hiring Python Developers for AI Projects lists the skills that matter beyond notebooks.
Checklist: is your pipeline production-ready?
- Logic lives in a versioned Python package; the notebook imports it.
- Each step has unit tests and the pipeline runs end to end on a sample partition in CI.
- Dependencies are pinned and the job runs in a container image.
- Every run is parameterised by date or partition and is safe to rerun.
- No local files or credentials in code; data passes through durable storage and secrets through a manager.
- Schema, volume, freshness and distribution checks run before data reaches a model or index.
- Model and index outputs are versioned and can be rolled back.
- Failures and missed runs alert a named owner, with a runbook.
- Costs of paid AI calls are tracked per run with a budget alarm.
- Consumers of each output are documented.
If more than three items are missing, schedule a hardening sprint before adding new AI features on top. It is far cheaper than debugging silent data problems in front of customers. For the wider operating model around models in production, see MLOps and LLMOps.
Frequently asked questions
Can we just schedule the notebook itself?
Tools exist to run notebooks on a schedule, and that can be a stopgap for a low-risk internal report. For customer-facing AI features, move the logic into a tested Python package so it can be reviewed, versioned, rerun safely and maintained by someone other than its author.
Do we need Airflow or Dagster from the start?
Not usually. One to a few independent jobs can run as containers triggered by a cloud scheduler. Adopt a full orchestrator when you have several interdependent jobs, regular backfills or multiple teams depending on the outputs.
How often should an AI pipeline run?
As often as the feature’s freshness requirement demands, and no more. Recommendations might refresh nightly, while a document assistant may need new files embedded within minutes, which suits event-driven processing rather than a batch schedule.
Who should own pipelines: data scientists or engineers?
Shared ownership works best. Data scientists own the logic and quality thresholds; engineers own structure, testing, deployment and monitoring. Each pipeline still needs one named owner for incidents.
What is the most common pipeline failure you see?
Jobs that are not safe to rerun, so a retry after a partial failure duplicates data or skips a period. Parameterising runs by partition and writing outputs with upserts or full overwrites prevents most of these problems.
Sources and methodology
Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.
- Apache Airflow: Best practices — accessed 9 November 2026. Idempotent tasks, upserts, fixed data intervals, no local storage, minimal top-level code and testing DAGs as production code.
- Google Cloud Architecture Center: MLOps continuous delivery and automation pipelines in machine learning — accessed 9 November 2026. Level 0 notebook-driven process, training-serving skew, and schema versus value skew in data validation.
- Sculley et al.: Hidden Technical Debt in Machine Learning Systems (NeurIPS 2015) — accessed 9 November 2026. Ongoing maintenance costs of ML systems and risk factors such as data dependencies and undeclared consumers.
- Dagster Docs: Concepts — accessed 9 November 2026. Asset-oriented orchestration, partitions for incremental processing and asset checks for data quality.
Related reading
Continue your research
Have an AI prototype stuck in a notebook?
Share what it does and where its data comes from. We will outline the pipeline, orchestration and monitoring needed to run it reliably.
