4

Simultaneous transactions could cause race conditions on a Solana program? For instance if we have the following counter example:

#[account]
pub struct Counter {
    pub number: u8,
}

#[derive(Accounts)]
pub struct UpdateCounter<'info> {
    pub payer: Signer<'info>,
    #[account(mut)]
    pub counter: Account<'info, Counter>,
}

pub fn update_counter(ctx: Context<UpdateCounter>) -> Result<()> {
    let counter = &mut ctx.accounts.counter;
    counter.number = counter.number + 1;
    Ok(())
}

And many users call update_counter() at the same time which would be the outcome? would it cause some transactions to fail? would the last transaction overwrite the number written by the previous user? Or would it work normally (No race conditions)?

1 Answer 1

2

Because the update_counter function doesn't take an argument, only an account, each transaction in the same block will just increment the counter by 1. So if you call 5 update_counter instructions / transactions in the same block, it will be 5 at the end of the block.

2
  • What would be the difference if it takes an argument instead? For instance that same 5 calls to update_counter using an argument with the same value 1, would we get the same result? Also, having all transactions accessing the same account is a recommended approach? I mean would this be performant in a scenario where there are about 10k simultaneous transactions? Sep 23, 2022 at 7:51
  • That's a much broader question that I can't comment on as to the "recommended approach" for updating the data on an account. If instead you had a function that said set_num(this_num) and all the transactions passed the same value for this_num then it would just be this_num at the end of the block.
    – Henry E
    Sep 23, 2022 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.