All workEssay 01 / 12

WeThaiInvest / A study in attention and time

The price moved.
The moment stayed.

A price touches a target, then moves away. Here is how an alert preserves that moment, verifies the condition and carries the result into a notification.

01 / OBSERVE

The last price can miss the moment.

Someone asks to be notified when a price reaches 235. It rises from 232.40 to 235.40, then falls to 234.60. A worker checking only the latest value would see a number below the target—even though the condition was met.

A price alert connects a person’s condition to an observed market event. For a one-shot alert, the outcome is final: once an eligible observation triggers it, later movements do not turn the same alert back on. That small promise shapes the observation, matching and storage decisions that follow.

Preserve the evidence between checks.

WeThaiInvest keeps a bounded observation window: the high, low, latest price and provider timestamps. The high can satisfy an upward condition; the low can satisfy a downward one. This preserves a threshold touch that would disappear if every new value simply replaced the previous one.

For an upward condition, a window high of 235.40 is evidence for a target of 235, even when the latest value is 234.60. For a downward condition, the equivalent evidence is the window low. Matching either extreme produces a candidate; the observation still has to belong to the alert’s eligible period.

The window is deliberately limited. It preserves enough evidence for matching without becoming a complete market-history archive. It also cannot recover a movement the provider never reported. Provider time matters here: receiving an old observation now does not make the underlying event new.

Try the price-window example
OBSERVATION DESK

A crossing can outlive the last price.

01 / INTERACTIVE STUDY
231233235237TARGET 235.00ARMED
Latest observed232.40
High after arming—
Accepted events00
Armed for the next observation

Only observations after arming count in this simplified example.

Illustrative prices, not market data. This study isolates threshold matching; it does not simulate index promotion, recovery or notification delivery.

02 / MATCH

Find the relevant conditions.

An incoming observation belongs to a symbol, so matching begins there. Redis sorted sets group conditions by symbol and direction, with target prices in order. The gateway searches a bounded range instead of scanning every user’s collection.

For an upward condition, the relevant targets are at or below the eligible window high. For a downward condition, they are at or above its low. An observation for one symbol does not need to examine conditions for unrelated symbols. The index makes the search smaller before the worker performs the more expensive checks.

The result is a set of candidates. The matching index narrows the search; the durable record still decides whether an alert is eligible. A condition may have been cancelled, expired or claimed by the time its candidate reaches the worker.

Price alert architectureBrowser requests go to the API, which checks the gateway quote, saves MongoDB and stages API Redis. The Go worker receives market events, writes the separate gateway cache and matches API Redis thresholds. The NestJS worker consumes candidates, commits a claim and outbox to MongoDB, then delivers notifications to the browser.RequestSaveStageCacheEventsConsumeDispatchClaim + outboxBrowserCreate an alertNestJS APIValidate & stageGateway HTTPCheck the quoteMongoDBState & outboxGateway RedisMarket cacheAPI RedisThresholds & streamsGo WSS workerObserve & matchNestJS workerVerify & commitMarket providerPrice eventsNotificationsIn-app · Push · Telegram
How a price observation becomes a notificationThe browser creates a condition through NestJS API, which validates a gateway quote and saves to MongoDB before staging API Redis. Market events reach the Go worker, which caches quotes separately in Gateway Redis and sends matching candidates through API Redis to the NestJS worker. The worker commits a claim and outbox in MongoDB, then dispatches notifications.JWTQuoteSaveConsumeDeliverClaim + outboxBrowserConditions & preferencesNestJS APIValidate & createGateway HTTPAuthoritative quoteMongoDBAlert state & outboxGateway RedisMarket cacheAPI RedisThresholds & streamsGo WSS workerObserve & matchNotificationsIn-app · Push · TelegramNestJS workerVerify, claim & recoverMarket providerAggregate events
01 / Architecture The gateway finds candidates. MongoDB owns the outcome. Delivery follows the committed intent.

Follow the two paths through the system.

The creation path begins in the browser. NestJS API validates the request and checks the quote through Gateway HTTP. MongoDB stores the alert before it is staged in the matching index. Saving the request and making it available to the matcher are separate handoffs, which is why an accepted alert needs an explicit pending state.

The observation path begins at the market provider. The Go WSS worker collects the price window, matches thresholds and appends candidates to API Redis streams. A NestJS worker consumes those candidates, verifies the durable record and commits the outcome before notification delivery begins.

The two Redis stores have different jobs. Gateway Redis holds the market cache. API Redis holds alert thresholds and coordinates candidate work. MongoDB owns alert state and notification intent. A cached quote, a matching index entry and a committed event each answer a different question.

03 / COMMIT

Verify the event before claiming it.

A new condition starts in PENDING_INDEX: the request has been accepted, but arming is not yet confirmed. It becomes ACTIVE after the arming acknowledgement. Keeping those states distinct makes the gap between database acceptance and index readiness visible.

Consider an alert created just after the price has already touched its target. The current window may still contain that earlier high. Without a time boundary, a newly created condition could borrow an observation from before it was ready. The observation fence prevents that older evidence from being mistaken for a new eligible event.

The worker checks state, expiry, the immutable condition and the observation fence. A direct claim from pending is possible only when the durable fence permits it. It is a guarded transition, not permission to skip verification whenever the index acknowledgement is late.

One-shot alert lifecyclePending becomes active after arming. Active can trigger, cancel or expire. Pending can also cancel or expire, and can trigger directly if the durable fence permits. All three outcomes are final.ArmedTarget verifiedUser cancelsDeadline reachedDirect trigger requires durable fencePENDING_INDEXAwaiting armingACTIVEWatching observationsTRIGGEREDClaim & outbox committedCANCELLEDFinal stateEXPIREDFinal stateAlso possible while pending
One-shot price alert statesPending becomes active after arming acknowledgement. Active can become triggered, cancelled or expired. Pending can also be cancelled, expire, or trigger directly when the durable fence permits. Terminal states never return to active.ArmedDirect claim if the durable fence permitsTarget metCancel pendingExpire pendingPENDING_INDEXAccepted, awaiting armingACTIVEArming confirmedTRIGGEREDClaim & outbox committedCANCELLEDStopped by the userEXPIREDDeadline reached
02 / Lifecycle Accepted is not yet armed. Triggered, cancelled and expired are final states; notification delivery has its own lifecycle.

Commit the decision and its message together.

An eligible claim changes the alert to TRIGGERED and writes its notification outbox entry in the same MongoDB transaction. The outbox is the durable record that a message should be processed. If the transaction does not commit, neither half should stand alone.

This matters when work overlaps. A candidate is evidence, not a reservation: cancellation, expiry or another claim may reach the record first. The authoritative transition must still be valid when it commits. TRIGGERED, CANCELLED and EXPIRED are terminal outcomes; processing an old candidate must not reopen them.

Notification delivery has its own lifecycle. Committing an alert means the system has recorded the event and the intent to communicate it. It does not mean a push provider accepted the message, Telegram delivered it or the person read it.

04 / RECOVER

Keep a way back when work is interrupted.

The index can drift from the database. A process may stop after saving an alert but before staging it, or leave an entry that no longer reflects durable state. Reconciliation repairs missing or inconsistent entries from the alert records. The fast representation is useful precisely because there is an authoritative place from which to repair it.

Protect the gaps between handoffs.

Matching appends candidate events before removing matched index members. Removing first would create a dangerous gap: if the stream write failed, the matcher would have forgotten the condition without leaving work for the consumer. Appending first preserves the handoff, though retries can still produce duplicate candidates.

A duplicate candidate must not claim an already-triggered record. A stable notification identity also reduces repeated internal work. These protections let processing recover without treating every retry as a new market event.

There is another gap after the transaction. The event and outbox entry may commit, then the immediate queue wake-up may fail. The outbox retains the intent so processing can resume from durable state. The queue helps work move quickly; it is not the only record that the work exists.

Keep the meaning intact at delivery.

Observation time, processing time and delivery time are different. A fast worker cannot make delayed market data current. The product must describe delayed observations honestly and distinguish the price that met the condition from the latest price someone sees when opening the chart.

Once the event is committed, the notification platform decides whether the message is still useful and which channels remain eligible. External delivery can still be uncertain—for example, when a provider accepts a request but its response is lost. Internal deduplication does not turn that uncertainty into proof of exactly-once delivery.

The trade-off is extra coordination: an index to reconcile, a stream to consume and an outbox to process. What those pieces buy is an explainable boundary at each step. The system can distinguish a price observation, a possible match, a committed alert and a delivery attempt without asking one status to mean all four.

Next: recipient policy and deliveryBefore the message, a decision.
CONTEXT / LINKS

Related work & references

Selected public entry points and related portfolio pages. A company website or profile is context, not a claim that private source code is available.

Scope, context & further questions

Based on the WeThaiInvest API and gateway implementation reviewed on 1 October 2026. The examples simplify the matching and delivery boundaries; they are not live quotes, production measurements or a complete replay of the engine.

  • Matching: Indexed candidates. The gateway queries sorted thresholds and records candidate events before removing matched index members.
  • Authority: Transactional decision. The API checks alert state, expiry, condition and arming fence before committing the outcome and outbox entry.
  • Recovery: Reconciliation. A background process repairs missing or inconsistent index entries from durable alert records.

Questions I am still working through

Why can an alert trigger when the latest price is back below the target?

The eligible observation window can contain a high that reached an upward target even when its final price is lower. The window provides evidence of the condition; the final price describes the latest observation in that window.

The interface still needs a clear way to distinguish the target, the observed range and the latest value without turning a short message into a market-data report.

Does one triggered alert guarantee exactly one message on every channel?

No. The durable alert transition and notification intent are protected separately from external delivery. Candidate deduplication does not prove that a provider delivered a message, or that a person read it.

Ambiguous provider outcomes require their own recovery policy and honest operational reporting.

Stories, products & useful placesEsc to close