Dec. 202612 Min. Read
From Shared Environments to Repeatable Integration Tests at MNTN
by The MNTN Team
Our backend service testing at MNTN was highly fragmented, with each team using its own approach, relying on a mix of ad hoc test scripts, varying levels of automation, and manual validation.
For instance, one team was saving SQL queries across multiple files that needed to be run in sequence to set up data and query the resulting tables, while another used Python scripts to export data to files, both of which then needed to be manually validated.
Despite these differences, they all depended on the same shared test environments. To manage shared usage, most teams kept a list of specific row IDs and their associated tests to track which data set belonged to each. That left a lot of room for test data to get mixed up. This led to slow testing cycles, which prevented us from iterating quickly and ultimately cost us time and money.
We knew that method had holes in it, and patching them one at a time wasn’t going to work. This is the story of how MNTN confronted this challenge, the choices we made, and the lessons we learned along the way.

Why shared environments stopped scaling
Our environments had deployed services, caches, and databases, across multiple environments, such as Production, Staging, QA, and Dev. Engineers would spin up services locally on their laptops, but they ultimately connected to shared databases or caches. This architecture created three bottlenecks, each making the next one worse.
Deployment and execution gridlock. The team executed its tests primarily in shared environments. Service deployments required coordination so that tests could run against known service versions or release candidates. Test execution needed the same coordination because without it, tests could hit the wrong versions and fail because they were validating features from another release.
Data was fragile and restores were destructive. Building data state from scratch was tedious because MNTN’s backend services operate on deeply relational campaign, budget, and audience data. The solution to this was to have lower environments rely on scheduled partial restores from production. Each restore would unknowingly wipe out test data, however, and engineers would spend days figuring out why their tests were suddenly failing.
Onboarding slowed. New team members ramping up tend to be a little more cautious with exploration, knowing that even your local version of the service reads and writes to a shared resource. No one wants to be the person who slows other teams’ development and testing because something unexpected changed in a shared environment. As a result, new team members took longer to fully onboard.
For these reasons, MNTN’s shared testing environments could not scale or operate efficiently. To ship reliably without investing in significant cross-team coordination and overhead, we needed a way to run tests with their own ephemeral dependencies and deterministic data.

The Pilot: Dynamic Campaign Optimization
MNTN’s Pacing squad, which ensures advertiser budgets are spent smoothly and effectively throughout a campaign, piloted the change to isolated testing environments with Dynamic Campaign Optimization (DCO). DCO is at the core of our Connected TV ad-serving pipeline. It ingests performance data and uses it to adjust campaign levers, such as daily budgets, frequency caps, and recency thresholds, in real time to meet an advertiser’s goals and pacing targets. Thorough integration test coverage was important because bugs in DCO directly affect live campaign spend.
DCO already had a strong suite of unit tests, but validating end-to-end behavior was difficult. It meant deploying a release candidate to the QA environment, hand-editing rows in the QA database, waiting for scheduled runs, and running verification scripts against the output. This approach was slow and couldn’t be automated reliably in continuous integration (CI).
This is when we decided to shift to containerized integration testing, where tests run against real dependencies like databases and message queues in ephemeral containers. We standardized on Python and pytest as our test runner and started with a simple prototype: DCO packaged alongside its direct dependencies, PostgreSQL, and ElasticMQ. In production, DCO connects to Amazon Simple Queue Service (SQS), but we decided to use the open-source ElasticMQ as a drop-in replacement. The whole environment setup was defined within a single docker-compose.yml file.

This setup lets engineers start up a locally isolated DCO environment in seconds and begin testing.
Seeding data with SQLModel
Solving runtime environment contention exposed a harder problem. DCO isn’t a standalone data producer and sits downstream of multiple services. This means an isolated environment with an empty database exercises almost none of its business logic.
Initially, we mounted raw .sql DDL scripts into PostgreSQL’s docker-entrypoint-initdb.d directory to build the database schemas. Then we wrote Python dataclasses and helper functions to insert rows per test. Over time, we consolidated both schema creation and test-data generation into SQLModel, a Python library combining SQLAlchemy and Pydantic that lets us work with database rows as regular Python objects. ORMs like it have a bad reputation for getting in the way of complex analytical queries, but we found that they excel at readable, type-safe test seeding.
import os
from decimal import Decimal
from sqlalchemy.engine import Engine
from sqlmodel import SQLModel, Field, Session, create_engine
class CampaignConfig(SQLModel, table=True):
__tablename__ = "items"
campaign_id: int = Field(primary_key=True)
owner_id: int = Field(default=1001)
daily_budget: Decimal = Field(default=Decimal("5000.00"))
strategy: str = Field(default="EVEN")
is_active: bool = Field(default=True)
def seed_campaign(session: Session, **overrides) -> CampaignConfig:
campaign = CampaignConfig(**overrides)
session.add(campaign)
session.commit()
session.refresh(campaign)
return campaign
def create_campaign_table(engine: Engine) -> None:
"""Create the items table if it doesn't already exist."""
SQLModel.metadata.create_all(engine, tables=[CampaignConfig.__table__])
if __name__ == "__main__":
# Local throwaway database only. Never point this at a shared environment.
url = os.environ.get(
"TEST_DATABASE_URL",
"postgresql+psycopg://postgres:postgres@localhost:5432/campaigns",
)
engine = create_engine(url)
create_campaign_table(engine)
with Session(engine) as session:
campaign = seed_campaign(session, daily_budget=Decimal("250.00"))
print(f"Created campaign {campaign.campaign_id}")
Models with sensible defaults changed how tests get written:
- Test intent is self-documenting. Instead of unreadable, multiline JSON fixtures or raw INSERT statements, we have clear test overrides for only the fields required for the test: seed_campaign(session, daily_budget(Decimal(“0.00”))). This reduced the time needed to decipher them by making it easy to understand the intent at a glance.
- No cross-test pollution. Since the database and ElasticMQ instance belong to the test run, an autouse fixture can be used to reset database tables and purge queues before every test run. This lead to reliable results and less time chasing flaky test failures caused by leftover data.
- Cross-team reuse. We packaged these SQLModel definitions into a shared Python library that lets adjacent teams generate valid test data without needing to understand every schema nuance. Adjacent teams can generate valid test data from a shared library, saving each team from having to rebuild schema knowledge and duplicate code.
- Synthetic data only. Test data is generated by the seeders from synthetic defaults, and the containers start empty, so no production data is copied into a test run. Teams can share tests freely without privacy or compliance concerns, since no production data is used for test runs.

Where the test boundary sits
A common trap in integration testing is pulling too many internal microservices into the test harness. You end up with environments that are difficult to manage, flaky tests, and wasting time on test failures with causes that are difficult to pinpoint. We wanted tests that isolate the service and don’t break when a neighboring service changes. The boundary we drew was to spin up stateful infrastructure (databases, queues, caches) and stub peer services.
Depending on the transport protocol, we use two primary stubbing tools:
- WireMock, an HTTP mock server, for REST dependencies and third-party external APIs.
- GripMock, a gRPC mock server, for internal gRPC services.
For less common cases, such as dependencies that require stateful multi-call handshakes, which declarative stubs can’t easily express, using lightweight custom fakes worked well.
With the service under test using something like WireMock, we can create mock endpoints that respond with the specific data we need. Before this setup, it would have been nearly impossible to manage shared mock rules. Testing calls to external partners was tedious too. Now we control the external response payloads, so tests can be as specific (and robust) as we want.
Why we moved off Docker Compose
The Docker Compose approach was a quick way to get started, but as our test suites grew in size and scope, managing containers outside of the Python test lifecycle created friction in two places:
- Startup configuration variance: Many MNTN services read environment variables once at boot. These variables are often feature flags or configurations that change how the service behaves. To test them, we had to maintain multiple Compose file overrides or manually restart containers before test runs. This began to reproduce one of our original bottlenecks, requiring manual coordination of environment and test execution, making it time consuming and error prone.
- Parallel execution limits: Static port bindings in docker-compose.yml prevented us from running multiple isolated environments side by side on the same machine or in the CI runner.
We solved both problems by migrating to container orchestration directly within our tests using Testcontainers (an open-source library for programmatically managing Docker containers inside test code). We no longer needed to manage static YAML files, and we could create reusable Python wrappers for our databases, queues, WireMock, and internal service containers. These wrappers were packaged and shipped alongside our data models, which allowed an engineer to spin up test environments and seed test data with minutes, instead of days.
import os
from decimal import Decimal
from sqlalchemy.engine import Engine
from sqlmodel import SQLModel, Field, Session, create_engine
class CampaignConfig(SQLModel, table=True):
__tablename__ = "items"
campaign_id: int = Field(primary_key=True)
owner_id: int = Field(default=1001)
daily_budget: Decimal = Field(default=Decimal("5000.00"))
strategy: str = Field(default="EVEN")
is_active: bool = Field(default=True)
def seed_campaign(session: Session, **overrides) -> CampaignConfig:
campaign = CampaignConfig(**overrides)
session.add(campaign)
session.commit()
session.refresh(campaign)
return campaign
def create_campaign_table(engine: Engine) -> None:
"""Create the items table if it doesn't already exist."""
SQLModel.metadata.create_all(engine, tables=[CampaignConfig.__table__])
if __name__ == "__main__":
# Local throwaway database only. Never point this at a shared environment.
url = os.environ.get(
"TEST_DATABASE_URL",
"postgresql+psycopg://postgres:postgres@localhost:5432/campaigns",
)
engine = create_engine(url)
create_campaign_table(engine)
with Session(engine) as session:
campaign = seed_campaign(session, daily_budget=Decimal("250.00"))
print(f"Created campaign {campaign.campaign_id}")
The session-scoped test fixtures handle most of the baseline path, while giving individual tests the flexibility to boot fresh containers when needed. Moving container lifecycles into pytest also let us parallelize via pytest-xdist.
Each pytest-xdist worker boots up its own dynamically mapped set of containers and uses it for its slice of tests. This isolated split allows us to keep running the tests as is and not worry about destructive fixtures like clean_state wiping the environment in the middle of another test run. Now a test suite that used to take more than 20 minutes finishes in under five.

The pilot was a success. Our containerized integration tests took minutes to run automatically for every new pull request, a process that used to require careful coordination, and hours to days of time. The next step was to scale this out to other squads.
One package for every squad
Once we had the container wrappers and SQLModel classes in a shared internal Python package, onboarding other teams beyond the Pacing squad became easy: new repositories had a pattern to follow instead of forcing engineers to come up with their own.
This architecture also let us incrementally expand the test boundary. We split tests into two scopes:
- Service-level suites: These tests live alongside the service code, booting only the service and close dependencies to verify business rules quickly.
- Pipeline-level suites: A separate project that composed two or more service wrappers together, feeding data into the service at the start of the pipeline and then validating output at the end.
We learned to start narrow and slowly widen the boundary only when the cross-service contract risk justifies the extra overhead. Pipeline-level suites turned out to be easy to assemble because the building blocks already existed.
The operational trade-offs
Like with every solution, this approach came with a couple of trade-offs.
- CI runner resources and image pulls: Spinning up multiple containers per pytest-xdist worker increases CPU and memory demands. A few ways to manage this overhead are through layer caching, pre-warmed base images, and session-scoped fixtures.
- Shared library maintenance: Our container wrappers and SQLModel classes are now treated as internal products and require ongoing ownership.
What changed for engineers
This approach has completely changed how our backend teams build and ship software:
- Deterministic CI gating: Integration suites now run automatically on pull requests across dozens of backend services, with reliable test results that can be reproduced, saving hours each release.
- Same-day local onboarding: New engineers can clone a repo and run pytest locally within minutes of their first day on the job, replacing the days of credential requests and broken QA test suites.
- Parallel CI execution: DCO’s over 300 integration tests running against real environments now run across four to five workers, cutting job time to about a quarter of what it was.
This whole experiment started because we wanted to tame testing for a single optimization service. It ended up giving us a repeatable pattern for backend integration testing across MNTN. For teams facing similar testing pains, our advice is to start with one service, isolate the environment via containers, and have your tests take control of data and state management. There are upfront costs, but the return on investment is well worth it. Next, we are extending this foundation with automated consumer-driven contract checks and onboarding additional core bidding and measurement services onto the shared container toolkit.