Chapter 21. Initializing Data in the Foundation Data Type

This chapter demonstrates a relatively simple concept: performing some initialization of data to be kept in the foundation data type. There are various reasons to do this, though the two most important are:

Efficiency

By initializing data once, at process startup, you can avoid having to recompute the same value in each request.

Persistence

We want to store some information in a mutable location that will be persisted between individual requests. This is frequently done via an external database, but it can also be done via an in-memory mutable variable.

Note

Mutable variables can be a convenient storage mechanism, but remember that they have some downsides. If your process dies, you lose your data. Also, if you scale horizontally to more than one process, you’ll need some way to synchronize the data between processes. We’ll punt on both of those issues here, but the problems are real. This is one of the reasons Yesod puts such a strong emphasis on using an external database for persistence.

To demonstrate, we’ll implement a very simple website. It will contain a single route and will serve content stored in a Markdown file. In addition to serving that content, we’ll also display an old-school visitor counter indicating how many visitors have been to the site.

Step 1: Define Your Foundation

We’ve identified two pieces of information to be initialized: the Markdown content to be display on the homepage, and a mutable ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.