Re-Checking a Customer List on a Schedule With the API

To automate list verification, run one small job every night: it picks the customer records whose last check is older than the interval you set for each checker, sends them to the TalismanLeads API as one order per checker, waits for the results and writes them back with today's date. Three things make it safe to leave alone: a spending cap checked against a free estimate, an Idempotency-Key saved with each batch so a crash or a second run never pays twice, and a resume step that finishes what the last run left open. This guide builds it in Python for a business re-checking its own customers' emails and phone numbers.
Why a customer list needs re-checking#
A phone number that was right last year may now belong to someone else: numbers are disconnected and given to new people, and others move to a new carrier or line type, as Why Phone Lists Go Stale explains.
Email addresses age too: people change jobs, abandon free mailboxes and let domains lapse. Email List Decay suggests re-verifying a business list every three months and a regularly mailed consumer list every six. A check is a snapshot; the job keeps each one younger than that.
What the nightly job does#
- Finish what the last run left open. Any saved batch not yet done is ordered again under its own key.
- Pick what is due for each checker, least recently checked first.
- Batch it to the 2,000-entry billing minimum and the 100,000-entry request limit.
- Guard the budget: read the balance, get a free estimate, stop if it is over your cap.
- Save the batch with its Idempotency-Key, then place the order.
- Follow the order until it finishes.
- Write the results back and mark the batch done.
Step 1: Decide what is due#
Keep a last checked date per record per checker, not one per customer: an email and a phone number age at different rates. The job keeps them, with each result, in a small checks table beside your customers.
Then give each checker its own interval. The sample re-checks emails every 90 days and runs the Number Carrier Lookup on phone numbers every 30, because a disconnected number can be given to someone new about six weeks later. Treat both as a starting point: if a run finds few changes, stretch the interval; if it finds many, shorten it.
Pick only customers who are still yours to contact: leave out closed accounts and anyone who unsubscribed. A re-check never turns an opt-out back into consent.
Step 2: Batch it to the minimum and the limits#
Every order is billed as at least 2,000 entries, on the API as on the website. GET /v1/checkers gives each checker's minimum_billed_entries, which can be higher for some checkers. So 1,240 due addresses cost the same as 2,000: on the Email Deliverability Checker, at $9.00 per 10,000 emails, that is $1.80 either way. Rather than pay for empty places, the job fills a small batch with the next-oldest records, which would come due soon anyway. The other choice is to wait until the minimum is due.
Three more limits shape a batch:
- Size. A request carries up to 100,000 entries (4 MB). The sample stops there, so a large backlog drains over a few nights; for one big batch, send it through
POST /v1/uploadsinstead, as How an Asynchronous Verification Job Works shows. - Country. Phone numbers in one order must be at least 90% from one country, or the order is refused with
mixed_countries. The sample's customers are all US numbers; with several countries, make one batch per country. - Duplicates. Two customers can share an address. The job sends each value once and writes the result back to every customer who has it.
A handful of calls a night stays far below the rate limits; on a 429 the job waits the seconds in Retry-After, as API Rate Limits and 429 Errors describes.
Step 3: Guard the budget#
Before every order the job makes two free reads:
GET /v1/accountreturnsbalanceandtrial_balance(trial credit, which is spent first). Together they are what the order can draw on.POST /v1/estimatesprices the exact batch and charges nothing.
If the estimate is over what is left of the run's cap (BUDGET_CAP), or over the funds, the job orders nothing for that checker and logs why. Otherwise it sends the estimate's charge as expected_charge, so the order is refused with price_changed rather than charged at a price you did not see. To check part of a batch rather than none, shrink it to fit the cap with the price from GET /v1/checkers.
Step 4: Carry the Idempotency-Key from the job run#
The key is what makes a scheduled job safe to repeat. The job makes one key per run and checker, such as recheck-2026-11-24-email_deliverability_checker, and saves it with the batch, its entries and the expected charge, before it sends the order. From then on, every attempt sends the same key with the same body:
- A request that times out, or a run that crashes while waiting, is picked up by the next run, which sends the saved request again. The API returns the order already placed (
200andIdempotent-Replay: true), or places it if it never arrived: charged once either way. - A second run on the same day finds the batch saved under that key and skips it. Had it rebuilt a different batch under the same key, the API would refuse it with
409 idempotency_conflictand place nothing. - On
insufficient_balancethe batch stays open, and the next run repeats it with the same key once you have topped up.
The run id is today's date when cron starts the job. On GitHub Actions, use GITHUB_RUN_ID, which GitHub keeps the same when a run is re-run. A key is remembered for 7 days, so the job leaves a batch older than six days to a person rather than send it again. The reasoning behind all of this is in Idempotency Keys.
What a re-run costs#
TalismanLeads reuses a recent result in one case. When the same account orders the same checker on the same set of entries again within the reuse window (24 hours unless TalismanLeads changes it; the docs say "within about a day"), under a new key, the new order is charged in full and may deliver the earlier result file instead of running a new check. The match ignores the order of the lines, repeats and blank lines, but one different entry means no match; a large order is matched part by part. Nothing in the order shows it: it reads completed, with the full charge.
So reuse never saves money; only the same key does. It also means a re-check belongs days after the last one, not hours: re-ordering a batch the same afternoon pays again for what may be the same answer.
Step 5: Follow the order and write the results back#
The job asks GET /v1/orders/{id} every 60 seconds (the docs ask for 30 or more) and treats a status it does not know as still running. Once the order has finished, GET /v1/orders/{id}/results gives a download link per part, good for 15 minutes; the link carries its own permission, so the API key never goes to it. A file is usually a zip holding all.csv, or a single CSV. Its first column is the entry as checked (email, then activated, for the Email Deliverability Checker); read columns by name, as more can be added.
Each result goes back to every customer with that entry, with the date:
- Completed: every entry in the batch is stamped. The Email Deliverability Checker checks Gmail, Yahoo, Outlook, iCloud, Yandex and Mail.ru addresses only and leaves others out of the result without charging for them, so an entry missing from a completed order is stamped too, with no result, or it would come back every night.
- Partially completed: a failed part is refunded automatically (
refundedshows how much). Its entries are not stamped, so they are still due and the next run picks them up. - Failed: the whole charge is refunded and nothing is stamped.
What to do with the results themselves (suppressing undeliverable addresses, updating a line type, flagging a record for review) is the subject of From Results File to CRM.
The complete job in Python#
The job keeps its records in SQLite so it runs as it stands: it expects a customers table with id, email and phone (E.164, such as +14155550142), and creates its own checks and batches tables. With your own CRM, change the queries and keep the logic. It needs the requests package and your key in TALISMANLEADS_API_KEY.
"""Re-check the customer emails and phone numbers that are due, through the TalismanLeads API.
Run it once a day from cron or any scheduler. An order that an earlier run left
unfinished is picked up again under its own Idempotency-Key, so a crash, a
timeout or a second run never pays for the same batch twice.
"""
import csv
import io
import json
import os
import sqlite3
import time
import zipfile
from datetime import datetime, timedelta, timezone
import requests
API = os.environ.get("TALISMANLEADS_API_URL", "https://api.talismanleads.io/v1")
AUTH = {"Authorization": f"Bearer {os.environ['TALISMANLEADS_API_KEY']}"}
NOW = datetime.now(timezone.utc)
RUN_ID = os.environ.get("RUN_ID") or NOW.strftime("%Y-%m-%d") # one run a day
BUDGET_CAP = 50.00 # the most one run may spend, in dollars
MAX_BATCH = 100_000 # the most entries one request can carry
CHECKS = { # checker id: (customer column, re-check every N days)
"email_deliverability_checker": ("email", 90),
"global_carrier_checker": ("phone", 30),
}
FINISHED = {"completed", "partially_completed", "failed"}
db = sqlite3.connect(os.environ.get("CRM_DB", "crm.db"))
db.executescript("""
CREATE TABLE IF NOT EXISTS checks (customer_id INTEGER, checker TEXT, checked_at TEXT,
result TEXT, PRIMARY KEY (customer_id, checker));
CREATE TABLE IF NOT EXISTS batches (key TEXT PRIMARY KEY, checker TEXT, entries TEXT,
charge TEXT, created_at TEXT, status TEXT DEFAULT 'open');
""")
class ApiError(Exception):
def __init__(self, code, message):
super().__init__(f"{code}: {message}")
self.code = code
def call(method, path, body=None, key=None):
"""One API request, waiting and repeating it when the API says to."""
headers = {**AUTH, **({"Idempotency-Key": key} if key else {})}
for _ in range(10):
r = requests.request(method, API + path, json=body, headers=headers, timeout=330)
try:
answer = r.json()
except ValueError:
answer = None # a gateway's 502 or 504 page
if r.ok:
return answer
code = (answer or {}).get("error", {}).get("code")
if r.status_code == 429:
wait = r.headers.get("Retry-After", "")
time.sleep(int(wait) if wait.isdigit() else 30)
elif answer is None or code == "order_status_unknown":
time.sleep(60) # the same request and key again: never charged twice
else:
raise ApiError(code, answer["error"]["message"])
raise ApiError("no_answer", f"{method} {path} kept failing")
def pick(checker, column, days):
"""Each distinct value, least recently checked first, and how many are due."""
rows = db.execute(f"""SELECT c.{column}, k.checked_at FROM customers c
LEFT JOIN checks k ON k.customer_id = c.id AND k.checker = ?
WHERE c.{column} <> '' ORDER BY k.checked_at""", (checker,))
last = {}
for value, checked_at in rows:
last.setdefault(value, checked_at) # never checked (NULL) sorts first
cutoff = (NOW - timedelta(days=days)).isoformat()
return list(last), sum(1 for at in last.values() if at is None or at < cutoff)
def new_batch(checker, key, budget_left):
"""Choose what is due, price it, and save it with its key before ordering."""
column, days = CHECKS[checker]
entries, due = pick(checker, column, days)
if not due:
return 0.0
info = next(c for c in call("GET", "/checkers")["checkers"] if c["id"] == checker)
# Every order is billed as at least minimum_billed_entries, so a small batch
# is filled up to it with the next-oldest checks instead of empty places.
entries = entries[:min(MAX_BATCH, max(due, info["minimum_billed_entries"]))]
quote = call("POST", "/estimates", {"checker": checker, "entries": entries})
account = call("GET", "/account")
funds = float(account["balance"]) + float(account["trial_balance"])
charge = float(quote["charge"])
if charge > budget_left or charge > funds:
print(f"{checker}: ${quote['charge']} is over the cap or the funds; nothing ordered")
return 0.0
db.execute("INSERT INTO batches (key, checker, entries, charge, created_at) VALUES (?, ?, ?, ?, ?)",
(key, checker, json.dumps(entries), quote["charge"], NOW.isoformat()))
db.commit()
return charge
def results_by_entry(order_id):
"""Every result row, keyed by the entry it is for (the file's first column)."""
rows = {}
for part in call("GET", f"/orders/{order_id}/results")["parts"]:
if not part["url"]:
continue # a failed part: refunded, nothing to read
data = requests.get(part["url"], timeout=300).content # no API key on this link
if data[:2] == b"PK": # a zip: read its all.csv
with zipfile.ZipFile(io.BytesIO(data)) as z:
data = z.read(next(n for n in z.namelist() if n.endswith("all.csv")))
reader = csv.DictReader(io.StringIO(data.decode("utf-8-sig")))
for row in reader:
rows[row[reader.fieldnames[0]]] = row
return rows
def run_batch(key):
"""Place (or find again) a saved batch's order, wait for it, write the results back."""
checker, entries, charge, created_at = db.execute(
"SELECT checker, entries, charge, created_at FROM batches WHERE key = ?", (key,)).fetchone()
if datetime.fromisoformat(created_at) < NOW - timedelta(days=6):
print(f"{key}: older than a key is kept (7 days); check this order by hand")
return
entries = json.loads(entries)
try:
order = call("POST", "/orders", {"checker": checker, "entries": entries,
"expected_charge": charge}, key=key)
except ApiError as e:
if e.code == "price_changed": # dropped: its entries are picked again tomorrow
db.execute("UPDATE batches SET status = 'dropped' WHERE key = ?", (key,))
db.commit()
print(f"{key}: {e}") # insufficient_balance stays open: repeated after a top-up
return
while order["status"] not in FINISHED: # an unknown status means still running
time.sleep(60)
order = call("GET", f"/orders/{order['id']}")
rows = results_by_entry(order["id"]) if order["status"] != "failed" else {}
column, stamp = CHECKS[checker][0], datetime.now(timezone.utc).isoformat()
for entry in entries:
if entry not in rows and order["status"] != "completed":
continue # in a failed, refunded part: still due, so picked again
db.execute(f"""INSERT INTO checks (customer_id, checker, checked_at, result)
SELECT id, ?, ?, ? FROM customers WHERE {column} = ?
ON CONFLICT (customer_id, checker) DO UPDATE
SET checked_at = excluded.checked_at, result = excluded.result""",
(checker, stamp, json.dumps(rows.get(entry)), entry))
db.execute("UPDATE batches SET status = 'done' WHERE key = ?", (key,))
db.commit()
print(f"{key}: {order['id']} {order['status']}, charged ${order['charge']}, "
f"refunded ${order['refunded']}")
def main():
for (key,) in db.execute("SELECT key FROM batches WHERE status = 'open'").fetchall():
run_batch(key) # an earlier run's order, under that run's key
spent = 0.0
for checker in CHECKS:
key = f"recheck-{RUN_ID}-{checker}"
if db.execute("SELECT 1 FROM batches WHERE key = ?", (key,)).fetchone():
continue # this run has already ordered it
charge = new_batch(checker, key, BUDGET_CAP - spent)
if charge:
spent += charge
run_batch(key)
if __name__ == "__main__":
main()We ran it against a stand-in for the API that lost the answer to the first order, answered with a 429, and had the job killed mid-wait. Each batch was ordered once: the lost answer and the resumed run got the same order back under the saved key, and a second run the same day ordered nothing.
Run it on a schedule#
On a server where the database lives, one crontab line is enough:
# Every day at 03:17 server time. flock skips a run while the last one is still going.
17 3 * * * cd /opt/recheck && . ./recheck.env && flock -n recheck.lock python3 recheck.py >> recheck.log 2>&1recheck.env holds export TALISMANLEADS_API_KEY=tl_live_... and is readable only by the job's user (chmod 600); API Key Security covers other places a key can live.
GitHub Actions works too, with a few rules from GitHub's documentation: a schedule cron runs in UTC, only on the default branch, and can be delayed when Actions is busy, most often at the start of each hour. In a public repository, scheduled workflows are switched off after 60 days without activity. Put the key in a repository secret, set RUN_ID to ${{ github.run_id }}, and give the workflow a concurrency group without cancel-in-progress, so a new run waits for the one in progress. The runner starts empty each time, so the database must be one it can reach over the network. A key made before November 8, 2026 may be held to your server's IP addresses and refused from a hosted runner.
A cloud scheduler (Google Cloud Scheduler, Amazon EventBridge Scheduler) follows the same rules: it starts the job, and the job's saved batches and keys make a late, doubled or retried start harmless.
Frequently asked questions#
How often should a scheduled re-check run?#
Run the job every day and let each checker's interval decide what goes in the batch: for example 90 days for emails and 30 for phone carrier data. Nightly runs keep the batches small and even.
Will re-running the job charge me twice?#
Not if the batch is saved with its Idempotency-Key before the order is sent, and every retry sends that key with the same body: the API returns the order already placed. A new key is a new order.
Does ordering the same list again return a fresh result?#
Not within about a day. The same checker on the same entries from the same account, under a new key, is charged as a new order and can return your earlier result rather than a new check. After the reuse window, it runs a new check.
What if fewer than 2,000 records are due?#
Every order is billed as at least 2,000 entries, so either fill the batch with the next-oldest records, as the job does, or wait until at least 2,000 are due. Each checker's minimum is in GET /v1/checkers as minimum_billed_entries.
Can the API tell my job when an order finishes?#
The API does not send webhooks. Follow the order with GET /v1/orders/{id} every 30 seconds or more; a nightly job has time to wait.
How do I keep a scheduled job from overspending?#
Read GET /v1/account and a free POST /v1/estimates before each order, stop when the estimate is over your cap or your funds, and send it as expected_charge.
The API documentation lists every endpoint and error code. Credits never expire, and businesses can try the API with a $5, 14-day free trial.
Was this helpful?


