# Stateless versus Stateful Transactions

Think back to your school math classes where you learned about, say, the square root function. You learned that you can call the function with an argument and it returns the result, e.g.,

(sqrt 9) 3

If you call it again with the same argument, you get the same result:

(sqrt 9) 3

This is called a stateless function.

Contrast that with the following function. The function mimics the situation of withdrawing
money from a bank account. The function is *withdraw* and it takes as argument an amount to be
withdrawn. It returns the balance remaining after withdrawal. For example, suppose you begin
with $100 in the account and withdraw $25:

(withdraw 25) 75

Call the function again with the same argument:

(withdraw 25) 50

Observe that the expression (withdraw 25), evaluated twice, yields different results. This is a different kind of behavior than that exhibited by the square root function. The withdraw function is a stateful function—it maintains a record of the balance and decrements that balance each time the function is called.

The withdraw function can be converted into a stateless function. Call it with two arguments: the amount to be withdrawn and a record of your transactions. Here is an XML document that records the initial balance and the first withdrawal:

<BankRecord> <InitialBalance>100</InitialBalance> <Withdrawal>25</Withdrawal> <CurrentBalance>75</CurrentBalance> </BankRecord>

Call the new withdraw function with the withdrawal amount and the BankRecord and it returns the updated BankRecord:

(withdraw 25 BankRecord) <BankRecord> <InitialBalance>100</InitialBalance> <Withdrawal>25</Withdrawal> <Withdrawal>25</Withdrawal> <CurrentBalance>50</CurrentBalance> </BankRecord>

If the new withdraw function is called again with the same arguments, it yields the same result.

With the new withdraw function the onus is on the user of the function to keep his records. In the previous—stateful—withdraw function the onus was on the function to keep the users' records.

Now let's turn our attention to web sites. Many are stateless and yet appear to
be stateful—they greet you Hello Roger, welcome back

and they remember your last
purchase Based on your last purchase, you might be interested in these books

. If
the web site is stateless then how is it doing this? Answer: behind the scenes
it creates a record on your behalf and stores that record on your machine. When
you visit the web site it retrieves the record from your machine and uses the
information in the record to greet you and locate books related to your last
purchase. This record is called a cookie.

Now you know the difference between a stateless and a stateful transaction.

For more information, see the book Structure and Interpretation of Computer Programs, p.219-220.

Here is a Polish translation of this article

Last Updated: July 17, 2014