Designing Subscription State for Telegram Bots
A member cancels automatic renewal on November 25. Your bot learns about it on November 27. The member's current access is paid through December 1.
On November 26, was renewal enabled? There are two useful answers. Based on the information your application had that day, it appeared to be enabled. Once the delayed confirmation arrives, your records may show that it had already been disabled. In either case, the member's paid access remains valid until December 1 under this example's cancellation policy.
That difference matters when support investigates a notification, a scheduled removal, or a member's complaint. A single active flag cannot explain what the application knew at the time and what later evidence says about the same period.
The model below separates those answers for a subscription service built around a Telegram bot. The dates and cancellation policy are illustrative.
Decide which question each state answers
When discussing a subscription, “active” can refer to several different things:
| Question | Example answer |
|---|---|
| What is the renewal setting? | Renewal is confirmed disabled. |
| Is there a pending operation? | A cancellation request is awaiting confirmation. |
| Is access currently authorized? | Yes, the paid interval has not ended. |
| What did Telegram last report? | The account was observed as a member at 09:00 UTC. |
| What remains to be done? | An access reconciliation task is pending. |
Each answer needs its own record. A cancellation request may still be waiting for confirmation. A member can have paid access without having received an invitation. And if a membership lookup fails, you still do not know whether the member is in the chat.
For a simple offer with one resource and one continuous paid period, a subscription record might hold paid_until, grace_until, a confirmed renewal_setting, and a separate cancellation request status. Store the payment evidence and access decisions that justify those values. If users can hold overlapping purchases, gifts, or access to multiple chats, one summary record is not enough: evaluate the individual grants for the relevant user and resource.
Telegram's editUserStarSubscription can cancel future extension of a Stars subscription. Its is_canceled=false setting allows the user to re-enable a previously canceled subscription; it should not be treated as proof that the user has already done so. The subscription must remain active through the current period for this operation. Other payment providers can have different cancellation semantics.
Use time as an input, not an update that must arrive
In this example, one paid period has already begun and ends at paid_until, with an inclusive start and an exclusive end. A separate, explicitly authorized grace interval can extend coverage beyond it:
- From the start of the paid period up to, but excluding,
paid_until: the period is covered by paid time. - From
paid_untilup to, but excluding,grace_until: the period is covered only if the grace allowance was actually authorized and recorded. - At or after
grace_until: neither of those intervals permits access.
When there is no grace, set grace_until equal to paid_until in this small example. A real grace policy might depend on a failed renewal, product terms, cancellation, or a manual exception; do not infer it merely because an invoice is unpaid. Coverage is one input to an access decision: a separate restriction or another grant can change the final result.
The result changes when the clock crosses a boundary, even if no webhook arrives. A cached answer therefore needs an expiration at its next relevant boundary and invalidation when supporting evidence changes. In a system with multiple grants or restrictions, compute the next relevant boundary across those records rather than using one global date.
Disabling future renewal is a separate fact. Under the policy used here, it does not remove time that has already been purchased. A refund or moderation restriction may change access under a different policy; neither should be silently represented as a renewal toggle.
Keep effective time and recorded time
Store at least two timestamps for a change:
- Effective time: when the confirmed change applies, if reliable evidence establishes it.
- Recorded time: when your application durably recorded that evidence. If receipt and persistence can be delayed separately, keep a receipt timestamp too.
These answer different support questions:
- What did the application know on November 26 about November 26?
- After receiving the delayed confirmation on November 27, what does the evidence say applied on November 26?
If the provider supplies no reliable effective time, keep it unknown or use a separately documented policy. Do not invent an earlier timestamp from the delivery time or the user's recollection.
For a trustworthy knowledge cutoff, keep prior versions and assign the recorded time from a trusted application or storage clock when the evidence is persisted. Do not backdate a correction's recorded time. Where multiple writers or equal timestamps make ordering ambiguous, define a durable ordering mechanism as part of the storage design; this small example does not implement one.
Consider one subscription with the following complete, illustrative snapshots. Each snapshot describes the same offer; all dates are in 2026 and UTC timestamps are shown without seconds for readability.
| Snapshot | Effective at | Recorded at | Renewal | Paid until / grace until |
|---|---|---|---|---|
| Initial | Nov 1, 09:00 | Nov 1, 09:00 | Enabled | Dec 1, 10:00 / Dec 1, 10:00 |
| Cancellation confirmed | Nov 25, 09:00 | Nov 27, 12:00 | Disabled | Dec 1, 10:00 / Dec 1, 10:00 |
The second row arrives late. For November 26, a query limited to snapshots recorded by that day returns the initial row. The same historical query, using snapshots recorded by November 28, returns the cancellation row. Neither answer means the application actually received the cancellation on November 25.
The November 25 effective time is an assumption in this scenario, not a field guaranteed by every notification. Telegram's BotSubscriptionUpdated describes the user, invoice payload, and a state such as canceled, active, or failed; it does not include a separate effective timestamp. In particular, failed describes a payment failure, not necessarily a change to the confirmed renewal setting. Keep a missing effective time unknown unless other reliable evidence or a documented policy establishes it.
A small SQLite example
The script below uses the two snapshots above to show how the answer changes with the knowledge cutoff. It runs locally with Python’s standard library and an in-memory SQLite database. Save it as subscription_state.py and run python3 subscription_state.py.
It assumes every stored snapshot is complete and internally consistent, the paid period has already started by the snapshot's effective time, revision orders corrections for the same effective instant, and every timestamp is a validated UTC string in the same fixed format. These assumptions let the example compare timestamps as text; the script does not validate their format. A real provider might not supply a sequence or an effective timestamp; the integration must define how it establishes and validates those facts.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE snapshots (
subscription_id TEXT NOT NULL,
effective_at TEXT NOT NULL,
recorded_at TEXT NOT NULL,
revision INTEGER NOT NULL,
renewal TEXT NOT NULL CHECK (renewal IN ('enabled', 'disabled')),
paid_until TEXT NOT NULL,
grace_until TEXT NOT NULL CHECK (grace_until >= paid_until),
PRIMARY KEY (subscription_id, effective_at, revision)
);
INSERT INTO snapshots VALUES
('s1', '2026-11-01T09:00:00Z', '2026-11-01T09:00:00Z', 1,
'enabled', '2026-12-01T10:00:00Z', '2026-12-01T10:00:00Z'),
('s1', '2026-11-25T09:00:00Z', '2026-11-27T12:00:00Z', 1,
'disabled', '2026-12-01T10:00:00Z', '2026-12-01T10:00:00Z');
""")
QUERY = """
WITH chosen AS (
SELECT renewal, paid_until, grace_until
FROM snapshots
WHERE subscription_id = :subscription_id
AND effective_at <= :valid_at
AND recorded_at <= :known_at
ORDER BY effective_at DESC, revision DESC
LIMIT 1
)
SELECT renewal,
CASE
WHEN :valid_at < paid_until THEN 'paid'
WHEN :valid_at < grace_until THEN 'grace'
ELSE 'expired'
END AS access_period
FROM chosen;
"""
def state(valid_at, known_at):
return db.execute(QUERY, {
"subscription_id": "s1",
"valid_at": valid_at,
"known_at": known_at,
}).fetchone()
instant = "2026-11-26T12:00:00Z"
print("as known Nov 26:", state(instant, instant))
print("as known Nov 28:", state(instant, "2026-11-28T12:00:00Z"))
print("at paid boundary:", state("2026-12-01T10:00:00Z", "2026-12-02T10:00:00Z"))
print("before any snapshot:", state("2026-10-31T12:00:00Z", instant))
The output is:
as known Nov 26: ('enabled', 'paid')
as known Nov 28: ('disabled', 'paid')
at paid boundary: ('disabled', 'expired')
before any snapshot: None
The first two results evaluate the same effective instant using different knowledge cutoffs. The final result does not label an unknown subscription as expired; it indicates that the example has no eligible snapshot. If the knowledge cutoff precedes the evaluated instant, the result is a projection based on information recorded so far, not proof of what will happen later.
The result classifies this one period; it is not a final access decision. The query does not account for a future start, other grants, or moderation restrictions, and it cannot tell whether the provider has changed since the last snapshot. The example also keeps everything in memory, so its records disappear when the process ends. A working service needs durable storage and a way to reconcile its records with the payment provider and Telegram.
Complete snapshots also have a maintenance cost. Suppose another snapshot was created on November 26 with renewal still marked enabled. Inserting the late November 25 cancellation alone would not fix the November 26 snapshot: the query would select the latter because it has a later effective time. One approach is to append a corrected revision for November 26 with its actual later recorded time, preserving the original revision for earlier knowledge cutoffs. That additional case is a design example, not included in the script. Rebuild or correct all affected projections from the underlying evidence; do not assume that arrival order is business order. Preserve prior versions rather than overwriting their recorded times.
If evidence is saved before a background projection is rebuilt, the database may temporarily contain the new evidence alongside stale snapshots. Commit the related changes together where practical, or track projection progress and mark affected answers as pending until the rebuild catches up. The script assumes its snapshots are already consistent; it implements neither approach.
Treat requests and confirmations as different records
Suppose a member presses “Cancel” while a provider is temporarily unavailable. A local request record can say pending; it cannot establish that future billing is disabled. The application should show the unresolved state and retain the request for retry or investigation.
Once a verified confirmation arrives, record its source, effective time if established, and recorded time. A request may fail, be retried, or have an uncertain outcome. If the billing system supports an authoritative lookup, use it during reconciliation rather than blindly claiming success.
Likewise, an approved checkout is not the same as a completed payment. For a Telegram Stars flow, SuccessfulPayment can contain subscription_expiration_date for recurring payments, but the field is optional. Use the actual contract and confirmed data for the integration. Avoid adding 30 days whenever a notification is delivered.
Keep Telegram observations separate from the decision
At 10:00, the entitlement may be valid while the account is absent because it has not joined yet, or because it left voluntarily. At 10:05, the entitlement may have expired while the account remains present because removal failed.
Record when you checked membership and what Telegram returned. If getChatMember fails, keep the observation as unknown or failed along with its time. Telegram guarantees that lookup for other users only when the bot is an administrator. A later check may give a different answer without changing the member’s payment history.
Before executing an expiry task, reload the current decision. A renewal or independent grant may have changed the answer after the task was created. A version check helps reject stale work, but it cannot make your database and the Telegram API share one transaction. If an API call is already in flight when the state changes, record the outcome and reconcile it with the latest authorized state.
Admission, removal, and re-entry have distinct effects. For example, Telegram's unbanChatMember permits a previously banned user to join again; it does not automatically re-add them. By default, calling it can remove an account that is currently a member; use only_if_banned=true when that behavior is not intended. A paid entitlement should not silently override an unrelated moderation ban.
Decide what a correction changes
When delayed evidence arrives, update the affected history and derive the current decision again. Then compare that decision with outstanding tasks and the latest membership observation.
Ask three separate questions:
- Historical explanation: What did the application know when it sent a reminder or queued a task?
- Corrected interpretation: What does the new evidence say was effective at that time?
- Current action: Given all current grants, restrictions, and observations, what work is justified now?
A corrected billing history does not automatically reverse a Telegram action that already occurred. If a valid member was removed while a renewal was being processed, follow a recovery policy that restores the ability to rejoin and tells the member what happened. If the member chose to leave, do not treat their absence as an instruction to add them back.
A historical query reconstructs an answer from the snapshots it can see; it does not prove which value a worker actually used. A stale cache, a delayed projection, or a failed API call can make the real execution differ. To investigate an action, record the decision time, relevant snapshot or grant versions, policy version, outcome, and any Telegram action result. Use that decision record alongside the historical query rather than treating a reconstruction as an execution log.
Where multiple payment events affect the same purchase, keep them separately identifiable and make the transaction that applies a business change safe to retry. A refund and its original payment are different events even if they refer to the same charge. Decide what a refund does to the affected grant. For example, the product policy might end access after a full refund while treating a partial refund differently.
Cases to check before launch
The table describes expected behavior for this article's policies; it is a test plan, not a report from a live Telegram integration.
| Scenario | Expected result |
|---|---|
| A cancellation request is submitted but not confirmed | Keep the request pending; do not claim future billing is disabled. |
| Cancellation is confirmed during an already-paid period | Preserve that paid interval unless another applicable policy changes it. |
| Confirmation arrives late | Keep both the effective and recorded times; distinguish the earlier knowledge from the corrected interpretation. |
The clock reaches paid_until with no authorized grace |
That paid interval no longer permits access at the boundary. |
| Grace is explicitly authorized | Treat the defined interval as covered by grace, not paid renewal; evaluate any separate restrictions before granting access. |
| A second independent grant still covers the resource | Do not remove access solely because the first grant ended. |
| A membership lookup fails | Keep membership unknown; do not rewrite billing or entitlement facts. |
| A renewal arrives while removal is in flight | Recompute the desired state and reconcile the result; do not assume a pre-call check prevents every race. |
For a managed service, these are also questions to ask before choosing the configuration. Nemiling's public documentation describes paid Telegram subscriptions and access management. It does not establish that Nemiling uses the schema, historical queries, or particular policies shown here; verify the behavior needed for the actual product and payment route.
Closing thought
When a member asks why they received an expiry notice, knowing whether their subscription is active now may not be enough. Support also needs to know what the system knew when it sent the notice and whether later evidence changed that picture.
Keeping payment evidence, access decisions, and Telegram observations separate makes those questions easier to answer—and gives the application a better basis for deciding what to do next.
About the author
- Exploring Telegram bots, SaaS, payments, automation, and developer tooling. I like breaking down how products work, where the technical trade-offs are, and what makes monetization flows reliable in practice.
Comments
Join the discussionNo comments yet. Be the first to comment.
