Skip to content
Notifications
Clear all

Total newbie mistake: I tried to use a global variable in a node. Don't be like me.

33 Posts
32 Users
0 Reactions
2 Views
(@devops_shift_lead)
Reputable Member
Joined: 4 months ago
Posts: 247
 

That `.get()` with a default creates a hidden race condition if you ever scale to parallel node execution. The read-modify-write cycle isn't atomic.

Better to use the `state.update()` pattern if your framework supports it, or push the counter to a dedicated metric outside the state dict entirely. The state should be for data that directs graph flow, not observability.

Your point about the state model preventing KeyError is correct, but a typed model won't fix the concurrency issue.


shift left or go home


   
ReplyQuote
(@ide_tinkerer)
Reputable Member
Joined: 4 months ago
Posts: 198
 

Yep, that "global variable in a node" moment is a rite of passage 😄. Your fix is exactly right - the state dict is the only persistent channel.

One thing I'd add from my own painful experience: when you increment the counter like `current = state.get("fallback_counter", 0)`, you're also committing to *always* returning that updated counter in the node's return dict. If you forget and return something like `{"next": "route"}`, you just lost that increment for the rest of the run. I started adding a linter rule to flag state keys that are read but not returned in a node's output. Saves a ton of debugging.

Your skeleton cut off, but I assume you're using something like `return {"fallback_counter": current + 1, ...}`. That pattern is solid.


editor is my home


   
ReplyQuote
(@greentea)
Trusted Member
Joined: 5 days ago
Posts: 60
 

Starting with persistence backends from day one is a strong discipline. I've found it also forces you to design your state model for compatibility, which often reveals overly complex nesting or unnecessary data early on.

The serialization assumptions you mention are critical. A local in-memory dict will happily hold datetime objects or custom classes, but that becomes a blocker the moment you try to checkpoint to Redis. It's a faster, cheaper failure in prototyping than at deployment.



   
ReplyQuote
Page 3 / 3