Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 6.1 (9 of 10): Twelve factors, part one

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

It works on my laptop

Aisha builds an app. It works on her laptop. She puts it on the server. It breaks.

A package is missing. The password is wrong. The folder is not there.

Twelve habits, called the twelve factors, stop most of these problems. Today you learn the first six.

Key words

WordWhat it meansExample
Twelve-factor appAn app built with twelve habits that make it easy to deploy.
DatabaseAn organised store of data that programs can search and change.
Version controlA tool that keeps every version of your files.
NetworkComputers joined together so they can send data to each other.
CodebaseAll the code of one app, kept in one repository.
RepositoryA store for code and its full history.
DeployTo put an app on a computer and start it. As a noun: one running copy of the app.
DependencyA package your code needs to run.flask
ConfigurationSettings that change between deploys.
Environment variableA setting stored where the app runs, outside the code.PORT=9000
Backing serviceA service your app uses over the network.
StatelessA process that keeps nothing on itself between requests.

The cells students fill in are left blank in this preview.

Six habits

Each factor is a short rule. It has a reason. Learn the reason and you can find the rule again.

Run the code below to see factor 3 at work: the configuration comes from outside the code.

Read a setting from outside the code

Code: python
import os

# Read a setting. If there is none, use "Hello".
greeting = os.environ.get("GREETING", "Hello")
print(greeting, "world")

# The code does not change. Only the setting changes.
# A setting that is missing should give a clear error, not a guess.

Make a free account to save your work and track your progress.

Factors 1 to 6

FactorRule in plain wordsWhy
1 CodebaseOne codebase in version control. Many deploys come from itTest and live run the same code
2 DependenciesWrite down every package you need. Keep them apart from other projectsA new machine installs the same things
3 ConfigKeep settings in the environment, not in the codeThe same code runs anywhere. No passwords in the repository
4 Backing servicesTreat a database or email service as a plug you can swap by changing a settingYou can change the database without changing the code
5 Build, release, runKeep three stages apart: make the program, add the settings, then run itYou can go back to an old release if the new one is bad
6 ProcessesRun as stateless processes. Keep data in a database, not in the processAny process can answer any request. One can die and nothing is lost

The cells students fill in are left blank in this preview.

Never put a password in code

Warning

Many people think a password in the code is safe. It is not, because code goes into a repository that many people read. A password there is shared with all of them. Keep passwords in the environment, never in version control.

Factor 5: three separate stages

flowchart LR
  code[Code from the repository] --> build[Build: make the program]
  build --> release[Release: program plus settings, with a version number]
  config[Settings for this deploy] --> release
  release --> run[Run: start the processes]

Swap a backing service with a setting

Code: python
import os


class MemoryStore:
    def __init__(self):
        self.items = []

    def save(self, item):
        self.items.append(item)

    def load(self):
        return self.items


class LoudStore(MemoryStore):
    def save(self, item):
        print("Saving", item)
        super().save(item)


# The setting picks the store. The rest of the code does not change.
name = os.environ.get("STORE", "memory")
store = LoudStore() if name == "loud" else MemoryStore()

store.save("tea")
print(store.load())

# Change "memory" to "loud" in the line that reads STORE and run again.
# A real app swaps a small database for a big one in the same way.

Make a free account to save your work and track your progress.

Why processes must be stateless

Code: python
class Process:
    def __init__(self, name):
        self.name = name
        self.basket = []      # kept inside this process

    def add(self, item):
        self.basket.append(item)

    def show(self):
        print(self.name, "sees", self.basket)


one = Process("process 1")
two = Process("process 2")
one.add("tea")
one.show()
two.show()      # the second process knows nothing

# Fix it: make one shared basket outside both processes.
# In a real app, that shared place is a database.

Make a free account to save your work and track your progress.

Match the factor to its rule

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Which factor is broken?

Have a go

Which factor is broken?

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Read the settings from the environment

Write the code that reads the settings, as a twelve-factor app should. read_settings takes the environment as a dictionary. It gives back the port, the debug flag and the database address. A missing database address is an error. missing_dependencies finds packages the code uses but nobody wrote down. Press Run Tests.

Code: python
def read_settings(env):
    # env is a dictionary of settings, like {"PORT": "9000", "DATABASE_URL": "db://x"}.
    # Give back a dictionary with three keys:
    #   "port"         the PORT setting as a whole number. If there is none, use 8000.
    #   "debug"        True if DEBUG is the text "true" (any case), else False. No DEBUG means False.
    #   "database_url" the DATABASE_URL setting.
    # If DATABASE_URL is missing, raise a ValueError. Never guess a password.
    return None


def missing_dependencies(declared, used):
    # declared: the list of package names written in the requirements file.
    # used: the list of package names the code imports.
    # Give back the names that are used but not declared, A to Z, with no repeats.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.