18 May 2009

Soft State in the PLT Web Server

posted by Jay McCarthy

Many Web applications and network protocols have values in the continuation that are necessary to complete the computation, but that may be recomputed if they are not available. This is “soft state”.

For example, a Web application may cache a user’s preferences from a database and deliver it to a Web browser as a hidden value; when the value is returned to the application in subsequent steps, it is used to customize the display. However, if the preferences were not available (or were corrupted in some way), the application could retrieve them from the database.

When using the PLT Web Server’s native continuations, this roughly corresponds to the use of a weak box: a box that the GC is allowed to erase the contents of. When using the PLT Web Server’s serializable continuations it roughly corresponds to a weak box and a weak hash table (that holds its keys weakly) to give the box a serializable value as an identifier.

This programming pattern is a bit difficult to get right. So, a library that implements it is now provided with PLT Scheme: web-server/lang/soft.

Here’s a trivial example:

#lang web-server

(provide interface-version start)
(define interface-version 'stateless)

(define softie
   (printf "Doing a long computation...~n")
   (sleep 1)))

(define (start req)
  (soft-state-ref softie)
  (printf "Done~n")
    (lambda (k-url)
      `(html (body (a ([href ,k-url]) "Done")))))))

Made with Frog, a static-blog generator written in Racket.
Source code for this blog.