Skip to main content

Asynchronous optimization

Media plan optimization is the one asynchronous flow of the TOM External API. You submit a definition and receive a job identifier immediately; the optimization runs in the background; you poll the job until it reaches a terminal status and then read the result.

1. What it does​

You give the optimization engine a set of candidate carriers, a criterion that tells it how to choose the next insertion and one or more objectives that tell it when to stop. It starts from an empty plan and adds insertions iteration by iteration: at each step it picks the insertion that best serves the criterion, until one of the objectives is reached or the plan cannot be improved any further. The result contains the plans of the last (up to) three iterations.

The user behind the API key needs the Study module. Jobs belong to that user and also appear in the background-jobs panel of the TOM web application.

2. Lifecycle of a job​

POST .../optimizations ──► 202 and a jobId
│
QUEUED ──► RUNNING ──► SUCCEEDED ──► EXPIRED (30 days after finishing)
│ ├──────► FAILED
│ └──────► CANCELLED
└──────────────────► CANCELLED
StatusTerminalMeaningResult call
QUEUEDNoAccepted and waiting for a free execution slot.409 AE_ERR_412
RUNNINGNoThe engine is calculating.409 AE_ERR_412
SUCCEEDEDYesFinished with at least one plan.200
FAILEDYesFinished without a result: the definition was rejected when the job started, another optimization of the same user was active, or an engine or infrastructure error occurred.409 AE_ERR_413 with the origin code
CANCELLEDYesCancelled outside this API, for example by the user in the TOM web application. A job can be cancelled while it is still QUEUED.409 AE_ERR_413
EXPIREDYesFinished successfully, but its result was deleted after the retention period.410 AE_ERR_414

The status can also go back: a RUNNING job returns to QUEUED when the platform reschedules it (it then runs again from the beginning), and a FAILED job returns to QUEUED if the user retries it from the TOM web application. The jobId stays the same. Always act on the latest status you read.

3. Polling contract​

  • Poll GET /api/v2/optimizations/{jobId} and wait at least retryAfterSeconds between two calls. It is a fixed recommendation (currently 30 seconds), not an estimate of the remaining time, and it is present only while the job is QUEUED or RUNNING.
  • Stop when status is SUCCEEDED, FAILED, CANCELLED or EXPIRED.
  • The response contains only the status and its timestamps (createdAt and, in terminal statuses, finishedAt). It has no progress, no partial plans and no failure reason: the result call returns those.
  • A run stops after one hour of execution. Time spent queued, the preparation of the run and any restart come on top of that hour, so a job can take longer than one hour to reach a terminal status. Choose your own give-up time accordingly and keep polling at a gentle pace.
  • Closing the connection after the 202 does not cancel the job.

4. Building the request​

POST /api/v2/survey/{surveyCode}/optimizations takes the survey in the path and the definition in the body. See the operation in the API reference for every field. In short:

FieldRequiredMeaning
workspaceIdYesOne of your workspaces, from GET /api/v2/workspaces. The engine takes the prices of the carriers from it. Always send it.
carriersYes, at least oneThe candidate carriers, by id, taken from the carriers list (items with type: CARRIER).
criterionYesCOVERAGE: pick the insertion that adds the most coverage. COVERAGE_PER_CPM: pick the one that adds the most coverage per unit of cost; it needs prices.
objectivesYes, at least oneThe stop conditions, each with a type and a value.
minMarginalCoverageNoThe minimum coverage gain, in percentage points, that an insertion must add to be chosen. From 0 to 100.
targetNoThe target audience, applied as a filter: the calculation counts only the people it selects. A saved target id or an inline TGL expression in filterTgl, never both.
targetBaseNoThe population base: the reference universe of the percentages. Same shape and rules as target, and independent of it: neither replaces the other.

Without target and targetBase, the optimization runs against the full universe of the survey. The id of a saved target comes from the targets of the workspace (GET /api/v2/workspace/{workspaceId}/survey/{surveyCode}/targets); the inline expression follows the TGL guide. Send an object with exactly one of id and filterTgl: both, or neither, is rejected with AE_ERR_411 and a message that names the field. tgl is a deprecated name of filterTgl that is still accepted (see Deprecated names); use filterTgl.

Each carrier accepts optional constraints: minInsertions (default 0), maxInsertions (default: no limit, and not lower than minInsertions), step (insertions added each time the engine selects the carrier; default 1, greater than 0), mandatory (at least one insertion) and price (net price per insertion; it replaces the price configured in the workspace).

Objective types:

typeReached when
BUDGETThe net cost of the plan reaches value.
COVERAGEThe coverage reaches value, in the same unit as stats.cover.
COVERAGE_PERCENTThe coverage percentage reaches value (at most 100).
GRPThe GRPs reach value.
CONTACTSThe contacts reach value, in the same unit as stats.contacts.

The run stops after the first iteration that reaches any objective, so the final plan can go slightly past the value (for example, spend a little more than the budget). Use a value greater than 0: a value of 0 or less is accepted but never stops the run. Send each type once.

A BUDGET objective and the COVERAGE_PER_CPM criterion need prices. A carrier's price is its price field or, if you omit it, the price configured in the workspace. If none of the candidate carriers has a price, the job ends FAILED. Send enumerated values in upper case, exactly as documented.

A request that needs no prices:

{
"workspaceId": "F780D8B99A1E513EE053CD6710AC7753",
"carriers": [{ "id": "TVCH1005D1F1" }, { "id": "TVCH1005D2F1" }],
"criterion": "COVERAGE",
"objectives": [{ "type": "GRP", "value": 150 }]
}

A request with constraints and prices that stops at the first of two objectives:

{
"workspaceId": "F780D8B99A1E513EE053CD6710AC7753",
"carriers": [
{ "id": "TVCH1005D1F1", "minInsertions": 2, "maxInsertions": 20, "step": 1, "price": 125.5 },
{ "id": "TVCH1005D2F1", "maxInsertions": 15, "mandatory": true, "price": 150.0 }
],
"criterion": "COVERAGE",
"objectives": [{ "type": "BUDGET", "value": 2450 }, { "type": "GRP", "value": 150 }],
"minMarginalCoverage": 0.1
}

A request for an audience (the filter) over a population base:

{
"workspaceId": "F780D8B99A1E513EE053CD6710AC7753",
"carriers": [{ "id": "TVCH1005D1F1", "price": 125.5 }, { "id": "TVCH1005D2F1", "price": 150.0 }],
"criterion": "COVERAGE",
"objectives": [{ "type": "BUDGET", "value": 2450 }],
"target": { "filterTgl": "EDA1.D3 AND SEX.D1" },
"targetBase": { "filterTgl": "SEX.D1" }
}

5. Two validation stages​

  1. At submit. The endpoint checks only the structure of the request and answers 400 when it is wrong. Only the first problem found is reported: a missing candidate carrier (AE_ERR_410), a missing objective (AE_ERR_409), an unknown criterion or objective type (AE_ERR_401), a target or targetBase with both or neither of the saved target id and the inline expression (AE_ERR_411), a field that the request does not define (AE_ERR_400) or a body that is not valid JSON (E400).
  2. When the job runs. Everything else is checked when the job starts: the rules above (maxInsertions not lower than minInsertions, step greater than 0, COVERAGE_PERCENT at most 100, minMarginalCoverage between 0 and 100), missing prices, a target or a base that cannot be resolved and another active optimization of the same user. A problem found then does not change the 202 you already received: the job ends FAILED, and the result call returns 409 AE_ERR_413 with the origin code.

The request is strict: an unknown field anywhere in it, in target, in targetBase, in a candidate carrier or in an objective, a misspelled one included, is a 400 (AE_ERR_400) whose message names the field and the object that contains it. Nothing is ignored silently, so a typo such as targetbase cannot make the optimization run without the base.

The surveyCode and the workspaceId are not validated at submit. A survey or workspace that cannot be used is reported later, through the outcome of the job.

6. Limits​

  • One optimization at a time per user. The engine runs one optimization at a time for each user, including optimizations open in the TOM web application. A job that starts while another optimization of the same user is active ends FAILED (origin code PO_ERR_100). Wait until the previous job reaches a terminal status before you submit the next one.
  • Queue. Each user can have up to 50 queued background jobs of any kind, including exports started in the TOM web application. Beyond that, the submit call returns 429 (JOB_USER_LIMIT_REACHED).
  • Duration. A run stops after one hour of execution. It still returns the plans found so far, with stopReason DURATION_CAP_REACHED.
  • Retention. Results are kept for 30 days after the job finishes. After that, a SUCCEEDED job becomes EXPIRED, and FAILED or CANCELLED jobs are deleted (404).
  • Not idempotent. Every accepted request creates a new job. Retrying a request that timed out can create a second job, which then competes with the first one.
  • No cancellation is available through this API, and there are no side effects: the result is data only, and nothing is written to a workspace.

7. Reading the result​

GET /api/v2/optimizations/{jobId}/result returns, for a SUCCEEDED job:

  • plans: one to three plans, oldest first; the last one is the final plan. Each plan has iteration, stats and carriers (the insertions assigned to each carrier, with the same id as in the request).
  • totalIterations: the number of iterations the engine executed. Only the last ones are returned in plans.
  • stopReason: why the run stopped.
  • objectives: the state of each objective of the request that has a value greater than 0, at the final plan.

The stats fields are all optional: read only the ones present. Today the API returns cover (an absolute figure), coverPercent, grp, contacts, cost, costPerGrp, cpmContacts, coverMax and totalInsertions. The other fields of the schema are not currently returned.

stopReasonMeaning
OBJECTIVE_REACHEDThe last plan reached at least one objective.
DURATION_CAP_REACHEDThe run was stopped after one hour of execution. The plans are the best found until then.
NO_FURTHER_IMPROVEMENTThe engine could not improve the plan further: no insertion was left to add, or the engine reached its maximum number of iterations.
ENGINE_ERRORThe run stopped for another reason after producing at least one plan. The plans are valid but can be far from the objectives: check objectives.

Each entry of objectives has type, target (the requested value), achieved, completedPercent (achieved divided by target, times 100, which can exceed 100) and reached. More than one objective can be reached at once. Switch on stopReason and on objectives; do not parse messages.

8. Outcomes that are not a result​

Job statusHTTP statuserrorCode
QUEUED, RUNNING409AE_ERR_412
FAILED, CANCELLED409AE_ERR_413
EXPIRED410AE_ERR_414
Unknown, owned by another user, or deleted404JOB_NOT_FOUND

For a FAILED job, errorMessage contains the origin code in parentheses, for example The optimization job failed (PO_ERR_100). A CANCELLED job has no code. The most common origin codes are listed in Errors and troubleshooting.

9. End to end​

This script submits an optimization, polls it and prints the final plan. It reads the base URL and the key from environment variables.

import os
import time
import requests

BASE_URL = os.environ["TOM_API_BASE_URL"]
HEADERS = {"X-API-Key": os.environ["TOM_API_KEY"]}
SURVEY_CODE = "APP_DEMO_2025"
TERMINAL = {"SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED"}

definition = {
"workspaceId": "F780D8B99A1E513EE053CD6710AC7753",
"carriers": [{"id": "TVCH1005D1F1"}, {"id": "TVCH1005D2F1"}],
"criterion": "COVERAGE",
"objectives": [{"type": "GRP", "value": 150}],
}

# 1. Submit. Do not submit another job until this one is terminal.
response = requests.post(
f"{BASE_URL}/api/v2/survey/{SURVEY_CODE}/optimizations",
headers=HEADERS, json=definition, timeout=130,
)
response.raise_for_status() # 202
job_id = response.json()["jobId"]

# 2. Poll, waiting at least retryAfterSeconds between calls.
give_up_at = time.monotonic() + 3 * 3600
while True:
status = requests.get(f"{BASE_URL}/api/v2/optimizations/{job_id}", headers=HEADERS, timeout=130)
status.raise_for_status()
job = status.json()
if job["status"] in TERMINAL:
break
if time.monotonic() > give_up_at:
raise TimeoutError(f"Job {job_id} did not finish in time")
time.sleep(job.get("retryAfterSeconds", 30))

# 3. Read the outcome.
result = requests.get(f"{BASE_URL}/api/v2/optimizations/{job_id}/result", headers=HEADERS, timeout=130)
if result.status_code == 200:
body = result.json()
final_plan = body["plans"][-1]
print(body["stopReason"], final_plan["stats"], final_plan["carriers"])
else:
error = result.json()
print(result.status_code, error["errorCode"], error["errorMessage"])