Articles / agentspythonlanggraph
Build an always-on AI agent in Python: scheduler, memory, approvals and crash recovery
A hands-on LangGraph and SQLite agent that wakes on a schedule, remembers past runs, waits for approval, and sends one email after a crash.
Most agent demos live inside one function call. A user asks, the model plans, tools run, the process exits, and everything the agent knew is gone. An always-on agent has four extra jobs. It starts itself on a schedule. It keeps its place in a half-finished run across process restarts. It carries facts from one run into the next. And it stops before anything risky until a person says yes.
This post builds one in about 170 lines of Python with LangGraph and SQLite, then kills it right after it sends an email and shows the restarted process finishing the run without sending a second one. The model is a stub behind one class, so the whole thing runs without an API key or a GPU.
Three earlier posts cover the theory, and this one does not repeat it. Long-running AI agent system design explains checkpoints versus workflow replay, retry policy and budgets. Agent memory system design covers what to store and how to rank it. Task planning AI agent in Python builds a validated planner and runs it on a real local model. Here the work is the wiring: how a scheduler, a LangGraph checkpointer, a memory table and an effect ledger fit together in one process you can leave running.
What we are building#
The agent sends a team a daily digest of new helpdesk tickets. Each morning it fetches tickets, skips the ones it already reported, writes a one-line-per-ticket digest, and asks a human before emailing it.
loop: every 30 s
|
v
+-------------+ resume runs left 'running' +-----------------------+
| scheduler |-------------------------------->| LangGraph thread |
| tick(now) | claim due job (CAS), new run | load_memory -> plan |
+-------------+-------------------------------->| -> step -> step ... |
| | -> save_memory |
| +-----------+-----------+
v |
agent.db (app data) checkpoints.db (SqliteSaver)
jobs next run per job one snapshot per super-step,
runs status per thread keyed by thread_id
memories facts that outlive runs
effects side-effect ledger step 2 is risky:
provider_outbox (stands in for the interrupt() -> wait for a human
email API) approve -> Command(resume=...)
Two SQLite files hold everything. checkpoints.db belongs to LangGraph and stores graph state per thread, so a run can pick up after a crash or a long pause. agent.db belongs to the app. Splitting them keeps the checkpointer's tables out of the way and makes the app data readable with plain sqlite3.
The LangGraph persistence docs draw the same line: a checkpointer is short-term, thread-scoped memory, and a store is long-term data that crosses threads. Here one scheduled run is one thread, and the memories table plays the store role.
| Table | Written by | Read by | Why it exists |
|---|---|---|---|
jobs |
init, scheduler |
scheduler | When each job runs next |
runs |
scheduler, drive() |
scheduler on startup | Which threads are mid-run, waiting, or done |
memories |
save_memory node |
load_memory node |
Facts that cross runs: preferences, ids already reported |
effects |
once() |
once() |
Did this side effect already happen? |
| checkpoints | LangGraph | LangGraph | Where each thread stopped |
Setup#
Tested on Python 3.15.2 with langgraph 1.2.24 and langgraph-checkpoint-sqlite 3.1.3 (the SQLite checkpointer is a separate package):
python3 -m venv .venv && source .venv/bin/activate
pip install langgraph langgraph-checkpoint-sqlite
No model download and no key. If LangGraph's node and edge model is new to you, read LangGraph explained from scratch first.
The full agent#
# agent.py - an always-on agent: schedule, plan, remember, pause for approval, survive a crash.
# LangGraph + SQLite. The model and the email provider are stubs, so no API key is needed.
import hashlib, json, os, sqlite3, sys, time
from datetime import datetime, timedelta
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import interrupt, Command
APP_DB, CKPT_DB = "agent.db", "checkpoints.db"
RISKY = {"send_email"} # tools that need a human yes
db = sqlite3.connect(APP_DB, isolation_level=None)
db.executescript("""
CREATE TABLE IF NOT EXISTS jobs(job_id TEXT PRIMARY KEY, user TEXT, goal TEXT,
every_min INTEGER, next_run TEXT);
CREATE TABLE IF NOT EXISTS runs(thread_id TEXT PRIMARY KEY, status TEXT);
CREATE TABLE IF NOT EXISTS memories(user TEXT, key TEXT, value TEXT, PRIMARY KEY(user, key));
CREATE TABLE IF NOT EXISTS effects(key TEXT PRIMARY KEY, status TEXT, result TEXT);
CREATE TABLE IF NOT EXISTS provider_outbox(idem_key TEXT PRIMARY KEY, body TEXT); -- the "email API"
""")
# ---- long-term memory: plain rows that outlive every thread ---------------
def recall(user):
return {k: json.loads(v) for k, v in
db.execute("SELECT key, value FROM memories WHERE user=?", (user,))}
def remember(user, key, value):
db.execute("INSERT OR REPLACE INTO memories VALUES (?,?,?)", (user, key, json.dumps(value)))
# ---- the model, behind one method. Swap in Ollama or an API here. ---------
class StubModel:
def plan(self, goal, memory):
# A real planner sends goal + memory to the LLM and parses JSON like this.
seen = memory.get("reported_ids", [])
return [{"tool": "fetch_tickets", "args": {"exclude": seen}},
{"tool": "write_digest", "args": {"style": memory.get("style", "short")}},
{"tool": "send_email", "args": {"to": "team@example.com"}}]
def digest(self, tickets, style):
sep = " | " if "line" in style else ", "
return sep.join(f"#{t['id']} {t['title']}" for t in tickets) or "no new tickets"
MODEL = StubModel()
# ---- tools ----------------------------------------------------------------
HELPDESK = {"2026-11-24": [(101, "Login 500s"), (102, "CSV export slow"), (103, "SSO loop")],
"2026-11-25": [(102, "CSV export slow"), (104, "Billing page blank"), (105, "API 429s")]}
def provider_send(idem_key, body): # fake email API that dedupes on a key
db.execute("INSERT OR IGNORE INTO provider_outbox VALUES (?,?)", (idem_key, body))
return "sent"
def provider_lookup(idem_key):
return db.execute("SELECT 1 FROM provider_outbox WHERE idem_key=?", (idem_key,)).fetchone()
def once(key, fn):
"""Run a side effect at most once per key, with a reconcile path after a crash."""
row = db.execute("SELECT status, result FROM effects WHERE key=?", (key,)).fetchone()
if row and row[0] == "done":
return json.loads(row[1]) | {"replayed": True}
if row and row[0] == "started" and provider_lookup(key):
result = {"status": "sent", "reconciled": True} # it went out before the crash
else:
db.execute("INSERT OR REPLACE INTO effects VALUES (?, 'started', NULL)", (key,))
result = fn()
if os.environ.get("CRASH_AFTER") == "send_email":
print(" !! process killed after the provider accepted the email")
os._exit(1) # no ledger update, no checkpoint
db.execute("UPDATE effects SET status='done', result=? WHERE key=?", (json.dumps(result), key))
return result
def run_tool(tool, args, results, day, key):
if tool == "fetch_tickets":
return [{"id": i, "title": t} for i, t in HELPDESK[day] if i not in args["exclude"]]
if tool == "write_digest":
return MODEL.digest(results["0"], args["style"])
if tool == "send_email":
return once(key, lambda: {"status": provider_send(key, results["1"])})
raise ValueError(f"unknown tool {tool}")
# ---- the graph ------------------------------------------------------------
class Run(TypedDict, total=False):
user: str; goal: str; day: str; memory: dict; plan: list; cursor: int; results: dict
def load_memory(s):
return {"memory": recall(s["user"]), "cursor": 0, "results": {}}
def make_plan(s):
plan = MODEL.plan(s["goal"], s["memory"])
print(f" planned {len(plan)} steps with memory {s['memory']}")
return {"plan": plan}
def step(s, config):
i = s["cursor"]; tool, args = s["plan"][i]["tool"], s["plan"][i]["args"]
key = f"{config['configurable']['thread_id']}:{i}" # run + step, never attempt
if tool in RISKY:
h = hashlib.sha256(json.dumps([tool, args, s["results"]], sort_keys=True).encode()).hexdigest()[:12]
answer = interrupt({"tool": tool, "args": args, "body": s["results"]["1"], "hash": h})
if answer.get("hash") != h or not answer.get("approved"):
print(f" step {i} {tool}: rejected, skipped")
return {"cursor": i + 1, "results": s["results"] | {str(i): {"status": "skipped"}}}
result = run_tool(tool, args, s["results"], s["day"], key)
print(f" step {i} {tool}: {result}")
return {"cursor": i + 1, "results": s["results"] | {str(i): result}}
def save_memory(s):
if s["results"]["2"].get("status") == "sent":
reported = sorted(set(s["memory"].get("reported_ids", [])) | {t["id"] for t in s["results"]["0"]})
remember(s["user"], "reported_ids", reported)
print(f" memory updated: reported_ids={reported}")
return {}
g = StateGraph(Run)
for name, fn in [("load_memory", load_memory), ("plan", make_plan), ("step", step), ("save_memory", save_memory)]:
g.add_node(name, fn)
g.add_edge(START, "load_memory"); g.add_edge("load_memory", "plan"); g.add_edge("plan", "step")
g.add_conditional_edges("step", lambda s: "step" if s["cursor"] < len(s["plan"]) else "save_memory")
g.add_edge("save_memory", END)
def drive(graph, thread_id, payload):
cfg = {"configurable": {"thread_id": thread_id}}
out = graph.invoke(payload, cfg, durability="sync")
if "__interrupt__" in out:
ask = out["__interrupt__"][0].value
print(f" waiting for approval: {ask['tool']} to {ask['args']['to']} hash={ask['hash']}")
status = "waiting"
else:
status = "done"
db.execute("UPDATE runs SET status=? WHERE thread_id=?", (status, thread_id))
print(f" run {thread_id}: {status}")
# ---- scheduler: one tick = resume crashed runs, then fire due jobs --------
def tick(graph, now):
for (tid,) in db.execute("SELECT thread_id FROM runs WHERE status='running'").fetchall():
nxt = graph.get_state({"configurable": {"thread_id": tid}}).next
print(f"resume {tid}: checkpoint says next node is {nxt}")
drive(graph, tid, None) # None = continue from the last checkpoint
due_jobs = db.execute("SELECT * FROM jobs WHERE next_run<=?", (now,)).fetchall()
print(f"tick {now}: {len(due_jobs)} job(s) due")
for job_id, user, goal, every, due in due_jobs:
nxt_run = (datetime.fromisoformat(due) + timedelta(minutes=every)).isoformat(timespec="minutes")
claimed = db.execute("UPDATE jobs SET next_run=? WHERE job_id=? AND next_run=?",
(nxt_run, job_id, due)).rowcount # compare-and-set claim
if not claimed:
print(f"{job_id}@{due}: another worker claimed it"); continue
tid = f"{job_id}@{due}"
if db.execute("INSERT OR IGNORE INTO runs VALUES (?, 'running')", (tid,)).rowcount == 0:
continue # this slot already has a run
print(f"fire {tid}")
drive(graph, tid, {"user": user, "goal": goal, "day": due[:10]})
if __name__ == "__main__":
cmd = sys.argv[1]
if cmd == "init":
db.execute("INSERT OR IGNORE INTO jobs VALUES ('ticket-digest','asha',"
"'Email the team a digest of new helpdesk tickets',1440,'2026-11-24T09:00')")
remember("asha", "style", "one line per ticket")
print("job and preference saved")
sys.exit()
with sqlite3.connect(CKPT_DB, check_same_thread=False) as conn:
graph = g.compile(checkpointer=SqliteSaver(conn))
if cmd == "tick":
tick(graph, sys.argv[2])
elif cmd == "loop": # always-on mode: one tick every 30 s
while True:
tick(graph, datetime.now().isoformat(timespec="minutes"))
time.sleep(30)
elif cmd == "approve":
tid, yes = sys.argv[2], sys.argv[3] == "yes"
ask = graph.get_state({"configurable": {"thread_id": tid}}).interrupts[0].value
db.execute("UPDATE runs SET status='running' WHERE thread_id=?", (tid,))
print(f"approve {tid}: {yes}")
drive(graph, tid, Command(resume={"approved": yes, "hash": ask["hash"]}))
How the pieces work#
The scheduler claims a slot, then names the run after it#
tick(now) does two things in a fixed order. First it resumes any run still marked running, because that status means a process died mid-run. Then it fires jobs whose next_run has passed.
Firing a job uses a compare-and-set update: UPDATE jobs SET next_run=? WHERE job_id=? AND next_run=?. If two workers read the same due row, only the first update matches, and the second sees rowcount == 0 and backs off. No lock table is needed.
The thread id is job_id@slot, such as ticket-digest@2026-11-24T09:00. Because the id comes from the schedule and not from a random UUID, a duplicate trigger for the same slot lands on the same thread, and INSERT OR IGNORE INTO runs refuses to start it twice. The same id becomes the prefix of every idempotency key in that run.
The loop command calls tick every 30 seconds with the wall clock. The tick command takes the time as an argument, so the demo below can jump from Tuesday to Wednesday without waiting a day.
Short-term state lives in the checkpoint, long-term facts live in a table#
The graph state (plan, cursor, results) is all a run needs to continue after a crash, and the checkpointer saves it after every node. drive() passes durability="sync", which the checkpointer docs describe as writing each checkpoint before the next step starts. The default, "async", writes while the next step runs and can lose the last checkpoint if the process dies. A digest job that runs once a day can easily afford a blocking write per step.
The executor is one step node that handles one plan step and loops back to itself through a conditional edge. That makes each plan step its own checkpoint. With all steps inside one node, a crash on step 3 would rerun steps 1 and 2.
Memory that should outlive the run goes in memories. load_memory reads it at the start, the planner turns reported_ids into an exclude argument and style into a digest format, and save_memory writes the new ids only if the email was actually sent. A rejected or failed run must not record tickets as reported, or they would vanish from the next digest.
A plain table was a deliberate choice. LangGraph's store API does the same job with namespaces and search, and the docs say its in-memory version is for development only, with Postgres, MongoDB and Redis stores for production. For two keys per user, a table you can SELECT and DELETE from by hand is easier to inspect and easier to clear when a user asks you to forget something.
The approval is bound to what it approves#
send_email is in RISKY, so the step node calls interrupt() with the tool, the arguments, the email body and a short hash of all three. The graph saves state and returns __interrupt__ to the caller. The process can exit; nothing waits in memory.
approve resumes the thread with Command(resume={"approved": ..., "hash": ...}). The interrupts docs state that on resume the node restarts from its first line, not from the interrupt() call, so code above the interrupt runs again and must be safe to repeat. In this node that code only reads state and computes the hash, which is why the side effect sits below the interrupt. The docs also warn against wrapping interrupt() in a bare try/except, since it pauses the graph by raising an exception.
The hash check rejects an approval given for different arguments. In this CLI the approver reads the hash from the current state, so it always matches. It starts to matter once approvals come from a Slack button or an email link created hours earlier: if a replan changed the recipient or the body in the meantime, the stale approval no longer releases the send. The test below covers that case.
Side effects go through a ledger#
once(key, fn) wraps every side effect. The key is thread_id:step_index, stable across retries and unique per run. The ledger has three states:
- No row: insert
started, call the provider, markdonewith the result. - Row is
done: return the saved result and do not call the provider. - Row is
started: a previous process died between calling the provider and recording the result. Ask the provider whether a message with this key exists. If yes, record it as done without sending. If no, send.
Case 3 is the crash that checkpoints alone cannot handle, because the provider and the checkpoint are different systems. The fix depends on the provider letting you look up a request by your key. The fake provider here has provider_lookup. For a real API without lookup, the long-running design post lists the alternatives (check-then-act on a tag, an outbox service, or a human gate).
A real run, with a crash in the middle#
The script below runs the whole story against fresh databases: the first morning's run pauses for approval, the approval process dies right after the provider accepts the email, a restarted process resumes, and the next morning's run uses what the first one remembered.
$ python agent.py init
job and preference saved
$ python agent.py tick 2026-11-24T09:00
tick 2026-11-24T09:00: 1 job(s) due
fire ticket-digest@2026-11-24T09:00
planned 3 steps with memory {'style': 'one line per ticket'}
step 0 fetch_tickets: [{'id': 101, 'title': 'Login 500s'}, {'id': 102, 'title': 'CSV export slow'}, {'id': 103, 'title': 'SSO loop'}]
step 1 write_digest: #101 Login 500s | #102 CSV export slow | #103 SSO loop
waiting for approval: send_email to team@example.com hash=dc856cdb811b
run ticket-digest@2026-11-24T09:00: waiting
$ CRASH_AFTER=send_email python agent.py approve ticket-digest@2026-11-24T09:00 yes
approve ticket-digest@2026-11-24T09:00: True
!! process killed after the provider accepted the email
exit code 1
$ python agent.py tick 2026-11-24T09:05 # restarted process
resume ticket-digest@2026-11-24T09:00: checkpoint says next node is ('step',)
step 2 send_email: {'status': 'sent', 'reconciled': True}
memory updated: reported_ids=[101, 102, 103]
run ticket-digest@2026-11-24T09:00: done
tick 2026-11-24T09:05: 0 job(s) due
$ python agent.py tick 2026-11-25T09:00
tick 2026-11-25T09:00: 1 job(s) due
fire ticket-digest@2026-11-25T09:00
planned 3 steps with memory {'reported_ids': [101, 102, 103], 'style': 'one line per ticket'}
step 0 fetch_tickets: [{'id': 104, 'title': 'Billing page blank'}, {'id': 105, 'title': 'API 429s'}]
step 1 write_digest: #104 Billing page blank | #105 API 429s
waiting for approval: send_email to team@example.com hash=e5eae9eb432f
run ticket-digest@2026-11-25T09:00: waiting
$ python agent.py approve ticket-digest@2026-11-25T09:00 yes
approve ticket-digest@2026-11-25T09:00: True
step 2 send_email: {'status': 'sent'}
memory updated: reported_ids=[101, 102, 103, 104, 105]
run ticket-digest@2026-11-25T09:00: done
$ sqlite3 agent.db "SELECT idem_key FROM provider_outbox"
ticket-digest@2026-11-24T09:00:2
ticket-digest@2026-11-25T09:00:2
Reading it top to bottom:
- Tuesday 09:00. The job fires and the thread is named after its slot. The planner sees only the saved style preference. Steps 0 and 1 run and are checkpointed, then step 2 pauses. The process exits normally with the run in
waiting. - The crash.
approveresumes the thread, the provider stores the email, andos._exit(1)kills the process before the ledger row becomesdoneand before LangGraph writes the step's checkpoint.os._exitskips cleanup handlers, so this is close to what akill -9or an out-of-memory kill would do. - Restart at 09:05. The run is still
running, sotickresumes it first. The checkpoint says the next node isstep, and step 0 and step 1 do not run again. Step 2 restarts from the top of the node. It did not pause for a second approval. The resume value fromapprovewas already stored with the thread, sointerrupt()returned it. The ledger finds thestartedrow, the provider confirms the key, and the result isreconciledwith no second send. - Wednesday 09:00. A new thread. The planner now sees
reported_ids: [101, 102, 103], so ticket 102, still open, is excluded and the digest lists only 104 and 105. - The outbox holds two emails, one per day. The fake provider also ignores a repeated key, so it would have caught a resend here too. Many real email APIs do not, and against one of those the ledger is the only thing standing between a restart and a second copy of Tuesday's digest.
Leaving it running#
python agent.py loop is the always-on mode. Started at 08:14 with a job set to 08:15, it idled through two ticks and fired on the third:
tick 2026-11-24T08:14: 0 job(s) due
tick 2026-11-24T08:14: 0 job(s) due
tick 2026-11-24T08:15: 1 job(s) due
fire ticket-digest@2026-11-24T08:15
planned 3 steps with memory {'style': 'one line per ticket'}
step 0 fetch_tickets: [{'id': 101, 'title': 'Login 500s'}, {'id': 102, 'title': 'CSV export slow'}, {'id': 103, 'title': 'SSO loop'}]
step 1 write_digest: #101 Login 500s | #102 CSV export slow | #103 SSO loop
waiting for approval: send_email to team@example.com hash=dc856cdb811b
run ticket-digest@2026-11-24T08:15: waiting
The run then waits until someone runs approve from another shell. To keep the loop alive across reboots, run it under systemd with Restart=always or in a container with a restart policy; dockerize an AI agent covers the image. The restart policy is what makes the resume code useful: the process will die, and on the way back up the first tick resumes anything it left behind.
Tests for the parts that fail quietly#
A happy-path run proves little. These three checks cover the claim race, a stale approval and a repeated side effect. Test 2 uses LangGraph's InMemorySaver, so it touches no checkpoint file.
# test_agent.py - three checks that matter more than the happy path.
import os, sqlite3, sys, tempfile
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.chdir(tempfile.mkdtemp()) # fresh agent.db for every test run
import agent
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
# 1. Two workers see the same due job; only one claim wins.
agent.db.execute("INSERT INTO jobs VALUES ('j','u','g',60,'2026-11-24T09:00')")
w1, w2 = (sqlite3.connect("agent.db", isolation_level=None) for _ in range(2))
due = [w.execute("SELECT next_run FROM jobs").fetchone()[0] for w in (w1, w2)]
claims = [w.execute("UPDATE jobs SET next_run='2026-11-24T10:00' WHERE job_id='j' AND next_run=?",
(d,)).rowcount for w, d in zip((w1, w2), due)]
assert claims == [1, 0], claims
# 2. An approval for different arguments does not release the email.
graph = agent.g.compile(checkpointer=InMemorySaver())
cfg = {"configurable": {"thread_id": "t1"}}
graph.invoke({"user": "u", "goal": "g", "day": "2026-11-24"}, cfg)
out = graph.invoke(Command(resume={"approved": True, "hash": "stale-hash"}), cfg)
assert out["results"]["2"] == {"status": "skipped"}
assert agent.provider_lookup("t1:2") is None
# 3. A finished side effect is replayed from the ledger, not run again.
calls = []
first = agent.once("k1", lambda: calls.append(1) or {"status": "sent"})
second = agent.once("k1", lambda: calls.append(1) or {"status": "sent"})
assert len(calls) == 1 and second["replayed"] is True
print("3 checks passed")
$ python test_agent.py
planned 3 steps with memory {}
step 0 fetch_tickets: [{'id': 101, 'title': 'Login 500s'}, {'id': 102, 'title': 'CSV export slow'}, {'id': 103, 'title': 'SSO loop'}]
step 1 write_digest: #101 Login 500s, #102 CSV export slow, #103 SSO loop
step 2 send_email: rejected, skipped
3 checks passed
Test 1 opens two separate connections, lets both read the due row, and checks that only one UPDATE wins. It runs the scheduler's SQL in two connections rather than racing two threads, which is enough to pin the compare-and-set logic. If you change the claim query, this test tells you whether you broke it.
Where the real model goes#
StubModel has two methods, plan(goal, memory) and digest(tickets, style). Everything else calls the model through them, so replacing the stub touches one class. A real plan sends the goal and the memory dict to the model, asks for JSON in the same shape as the stub returns, and validates it before the graph uses it. The task planning post has a working version that calls a 4B model through Ollama's chat API with a JSON schema, plus the validator that catches plans which are valid JSON but name wrong tools or arguments.
Two rules carry over to a real model in this design. Keep the model call in its own node (here, plan) so a crash later in the run does not pay for it again; the checkpoint already holds the plan. And never let the model write memories directly. In this agent, code writes memory from tool results that actually happened, which keeps a hallucinated "I already reported ticket 106" out of tomorrow's run.
What breaks first in production#
| Problem | Where it shows up in this code | What to change |
|---|---|---|
| Backlog after downtime | Down for three days, the loop fires three missed slots on three ticks, because next_run moves forward one interval per claim |
Skip to the next future slot, or use APScheduler's coalesce and misfire_grace_time; its user guide says coalescing is off by default |
| Two workers resume the same run | tick treats every running run as crashed, including one another worker is executing right now |
Add a lease column: worker id plus expiry, renewed while the run is active; resume only expired leases |
| SQLite write contention | Several processes writing agent.db and checkpoints.db get database is locked |
Turn on WAL mode and a busy timeout for a single host; move to Postgres and PostgresSaver for more than one |
| Approvals that never come | A waiting run sits forever |
Store a deadline with the interrupt and have tick resolve expired ones with a default action |
| Provider has no lookup | once() case 3 cannot tell whether the email went out |
Put a gate on the step, or check for the message by a tag before sending |
| Checkpoints pile up | One thread per day per job, never deleted | The persistence docs suggest pruning old checkpoints on a schedule |
| Memory grows without limit | reported_ids gains every ticket ever reported |
Keep a window (last 30 days) or store the newest reported id instead |
None of these show up in a one-day demo. The backlog row shows up the first time the server is off over a weekend, so fix that one before the first deploy.
When this is the wrong tool#
If the job is "run this script at 9 AM", cron plus a script that writes its result somewhere is simpler and has fewer failure modes. The pieces here start paying off once a run waits on a person, has a side effect you cannot repeat, or needs to know what the previous run did. This agent does all three, which is why it has a checkpointer, a ledger and a memory table. If your job does only one of them, keep only the matching piece.
Sources#
- LangGraph persistence: checkpointers versus stores, pruning old checkpoints
- LangGraph checkpointers: durability modes, pending writes,
SqliteSaver - LangGraph interrupts:
interrupt(),Command(resume=...), node restart on resume - LangGraph stores: in-memory store for development, persistent stores for production
- langgraph on PyPI and langgraph-checkpoint-sqlite on PyPI
- APScheduler 3.x user guide: misfires and coalescing
- SQLite write-ahead logging
- Ollama chat API