# Stable memory is not synchronous for some reason

**URL:** <https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758>\
**Category:** Rust\
**Created:** [May 2, 2025, 8:33am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758 "2025-05-02T08:33:43Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 2, 2025, 8:33am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/1 "2025-05-02T08:33:43Z")

</div>

Hi dev, I have this weird situation with stable memory.

I have an API create a record on stable Btree `process_action`. What it does:

1. Finding the action is existed or not, find by key prefix example code

```auto
store
.range(prefix.clone()..)
.filter(|(key, _)| key.starts_with(&prefix))
.map(|(_, value)| value.clone())
.collect();

```

1. If not create the record
2. Else update the record with input

But when frontend call this method 3 times in very short time

 ![Screenshot 2025-05-02 at 15.31.51](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/3X/1/2/12f937182216a9d691d3bf3d9f798e4d25da4ed3.png)  
 ![Screenshot 2025-05-02 at 15.30.25](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/3X/2/3/23cda27817ecb10eed88d765560f9b9f837fe819.png)

The log show me that the step 1 didn’t find the record for 3 calls, and it created 3 records with different ids.

Can someone explain me why stable memory is not synchronous in this case?

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 2, 2025, 8:51am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/2 "2025-05-02T08:51:59Z")

</div>

> [@baolongt](#):
>
> frontend call this method 3 times in very short time

You make three separate calls, each of which triggers a separate message execution. That alone lets me expect different timestamps, especially locally. I suspect there is some misunderstanding somewhere. Why do you think the timestamp changing between calls shows that stable memory access is async? (also, if your function is not `async` then there is no way (\*assuming you don’t do something extremely weird) for the function to do async work)

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 2, 2025, 9:57am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/3 "2025-05-02T09:57:14Z")

</div>

I don’t know but it happened in very small of time and the logs said me each call doesn’t find the record, I just thinking it is not async

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 2, 2025, 10:00am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/4 "2025-05-02T10:00:50Z")

</div>

I wrote a [unit test](https://github.com/CashierHQ/cashier/blob/staging/src/test/link/duplicate_link.spec.ts#L49) for testing via PicJS

but seems it work correctly, I don’t know why it doesn’t work while I did it on frontend

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 2, 2025, 10:20am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/5 "2025-05-02T10:20:19Z")

</div>

I suspect this async method call made next call cannot be handle correctly

1. Finding the action is existed or not, find by key prefix example code
2. If not create the record  
2.1 Call to ledger canister to check have enough balance (async)  
2.2 create record and store
3. Else update the record with input

@Vivienne Is this possible to cause this issue  
I think it is, just read the [docs](https://internetcomputer.org/docs/references/async-code#:~:text=When%20a%20canister%20C1%20calls%20a%20canister%20C2%2C%20C1%20can%20process%20other%20calls%20while%20waiting%20on%20the%20response%20from%20C2.%20This%20significantly%20increases%20the%20canisters%27%20scalability)

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 2, 2025, 11:25am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/6 "2025-05-02T11:25:23Z")

</div>

We may not be using the same words for the same things. Let me try to explain in my words what you are doing.

- Check if the record exists in the StableBtree
  - This uses synchronous stable memory to fetch the (in this case nonexistent) record

- The record does not exist, so you start the process to create it:
  - Start with an async call to the ledger. This is an inter-canister call as described in your docs link. Other calls may be processed now.

- Once the inter-canister call completes, you have the info to create the record
  - Use synchronous stable memory access to create the record

If you run multiple attempts in parallel the system may (as in your frontend-triggered scenario) or may not (as in your PicJS test) interleave the multiple calls. If they are interleaved, then you have a race condition where you create records multiple times (as you observed in the logs). The proper way to deal with this is to introduce some application-level locking so you don’t create the same record multiple times. You could e.g. create the record in a ‘under construction’ state before doing the ledger call. Then other requests will see that the record is getting created already.

The whole process is not synchronous (since you make an inter-canister call), but that doesn’t mean that stable memory access is not synchronous. Does my explanation/rewording make sense to you?

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 2, 2025, 4:04pm UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/7 "2025-05-02T16:04:59Z")

</div>

thank for the explaining, it make sense

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 13, 2025, 6:57am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/8 "2025-05-13T06:57:04Z")

</div>

Hi @Vivienne, I might need your help for this situation

The backend does this in one method :

- make a transaction’s state ‘created’
- make a transaction’s state to ‘in progress’
- make ledger calls, related to the transaction
- make the transaction’s state to ‘success’

If the frontend poll the status of the transaction in between these steps, I only get ‘created’ state.  
And when the call finished the the ‘success’ state returned.

When does the updated state can be query from client (http agent)?

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 13, 2025, 8:55am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/9 "2025-05-13T08:55:22Z")

</div>

Queries can only read committed state changes. State changes are committed (assuming no panics) when a message finishes processing, or whenever you `await` something [EDIT: something external]. An extra difficulty is that (as in any distributed system) not all replicas may be fully up to date.

Also, does this happen on mainnet or locally? I could imagine that locally PocketIC is too fast to expose the intermediate state. On mainnet you need to make cross-subnet calls to make the ledger transactions. In that case I would say that a bug is more likely than hitting stale state repeatedly

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 13, 2025, 9:14am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/10 "2025-05-13T09:14:28Z")

</div>

it happen in mainnet. This process loop n times (based on config) - in one method called.

I tried with n = 3, for each loop  
it take me 6-8 second to finished the ledger call - cross-subnet calls

But it seems the state is not committed during the loop

do you think because my syntax cause un commited state?  
the code I asked wrote in `tx_manager_service.rs` but it await by a lot of layer in `api.rs`

`api.rs`

```rust
#[update(guard = "is_not_anonymous")]
pub async fn update_action(input: UpdateActionInput) -> Result<ActionDto, CanisterError> {
    let api: LinkApi<RealIcEnvironment> = LinkApi::get_instance();
    
    let res = api.update_action(input).await;

    let end = ic_cdk::api::time();

    res
}

// LinkApi impl
 pub async fn update_action(
        &self,
        input: UpdateActionInput,
    ) -> Result<ActionDto, CanisterError> {
        let caller = ic_cdk::api::caller();

        let is_creator = self
            .validate_service
            .is_action_creator(caller.to_text(), input.action_id.clone())
            .map_err(|e| {
                CanisterError::ValidationErrors(format!("Failed to validate action: {}", e))
            })?;

        if !is_creator {
            return Err(CanisterError::ValidationErrors(
                "User is not the creator of the action".to_string(),
            ));
        }

        let args = UpdateActionArgs {
            action_id: input.action_id.clone(),
            link_id: input.link_id.clone(),
            execute_wallet_tx: true,
        };

        let update_action_res = self
            .tx_manager_service
            .update_action::<fn(ActionState, ActionState, String, ActionType, String)>(args, None)
            .await
            .map_err(|e| {
                CanisterError::HandleLogicError(format!("Failed to update action: {}", e))
            });

        update_action_res
    }

```

tx\_manager\_service.rs

```auto
pub async fn update_action<F>(){
    // do some thing
        for mut tx in eligible_canister_txs {
               // where I set the tx to `in progress`
                self.execute_tx(&mut tx).map_err(|e| {
                    CanisterError::HandleLogicError(format!("Error executing tx: {}", e))
                })?;

                // ledger call
                self.execute_canister_tx(&mut tx).await?;
            }

   // do something
}

```

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 13, 2025, 10:13am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/11 "2025-05-13T10:13:42Z")

</div>

> [@baolongt](#):
>
> But it seems the state is not committed during the loop

Correction from before: anytime you `await` a call to some other canister is a commit point, not every `await` in general. Should have thought of that.

Your code looks fine to me. I even checked the implementation of `self.execute_canister_tx` in the repo you linked above and didn’t find anything suspicious. Let me ask some other people if I’m missing something obvious…

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 13, 2025, 10:17am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/12 "2025-05-13T10:17:47Z")

</div>

Maybe some ‘stupid’ things to double-check in the meantime:

- Are you polling fast enough?
- If you fetch the tx state just before executing the call, is it actually ‘in progress’?
- Are you fetching the state for the right action?

---

<div class="post-metadata">

**Author:** ![mraszyk](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/mraszyk/32/7945_2.png) [@mraszyk](https://forum.dfinity.org/u/mraszyk)\
**Post date:** [May 13, 2025, 11:17am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/13 "2025-05-13T11:17:49Z")

</div>

> [@Vivienne](#):
>
> I could imagine that locally PocketIC is too fast to expose the intermediate state.

`dfx start --artificial-delay 10000` would introduce a delay of 10s in between rounds so it should be possible to inspect the state at the end of every round

---

<div class="post-metadata">

**Author:** ![mraszyk](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/mraszyk/32/7945_2.png) [@mraszyk](https://forum.dfinity.org/u/mraszyk)\
**Post date:** [May 13, 2025, 11:50am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/14 "2025-05-13T11:50:32Z")

</div>

> [@baolongt](#):
>
> cross-subnet calls

This is also crucial for being able to observe the “processing” state. If the ledger canister is on the same subnet as your backend canister, then all calls could be executed within the same round and thus you’d never see the intermediate state.

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 13, 2025, 7:14pm UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/15 "2025-05-13T19:14:50Z")

</div>

Hey thanks for this advice. It work, turn out our frontend called wrong API

---

<div class="post-metadata">

**Author:** ![baolongt](https://avatars.discourse-cdn.com/v4/letter/b/4491bb/32.png) [@baolongt](https://forum.dfinity.org/u/baolongt)\
**Post date:** [May 13, 2025, 7:19pm UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/16 "2025-05-13T19:19:11Z")

</div>

@Vivienne@mraszyk  
Thanks for explaining how the committed state change work.

I found that the document didn’t well written for committed state. The only document relate that AI can find is this one and it is for motoko.

> **[Actors | Internet Computer](https://internetcomputer.org/docs/motoko/main/writing-motoko/actors-async#traps-and-commit-points)**
>
> The programming model of the Internet Computer consists of memory-isolated canisters communicating by asynchronous message passing of binary data encoding Candid values. A canister processes its messages one-at-a-time, preventing race conditions. A...

---

<div class="post-metadata">

**Author:** ![Vivienne](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/vivienne/32/29170_2.png) [@Vivienne](https://forum.dfinity.org/u/Vivienne)\
**Post date:** [May 14, 2025, 9:36am UTC](https://forum.dfinity.org/t/stable-memory-is-not-synchronous-for-some-reason/45758/17 "2025-05-14T09:36:02Z")

</div>

Thanks for the feedback! @Jessie, maybe you’re interested in this?
