Logic and Lattices for Distributed Programming

Neil Conway
UC Berkeley
nrc@cs.berkeley.edu

William R. Marczak
UC Berkeley
wrm@cs.berkeley.edu

Peter Alvaro
UC Berkeley
palvaro@cs.berkeley.edu

Joseph M. Hellerstein
UC Berkeley

hellerstein@cs.berkeley.edu

David Maier
Portland State University
maier@cs.pdx.edu

ABSTRACT
In recent years there has been interest in achieving application-level
consistency criteria without the latency and availability costs of
strongly consistent storage infrastructure. A standard technique is to
adopt a vocabulary of commutative operations; this avoids the risk
of inconsistency due to message reordering. Another approach was
recently captured by the CALM theorem, which proves that logically
monotonic programs are guaranteed to be eventually consistent. In
logic languages such as Bloom, CALM analysis can automatically
verify that programs achieve consistency without coordination.

In this paper we present BloomL, an extension to Bloom that
takes inspiration from both of these traditions. BloomL generalizes
Bloom to support lattices and extends the power of CALM analysis
to whole programs containing arbitrary lattices. We show how the
Bloom interpreter can be generalized to support eﬃcient evalua-
tion of lattice-based code using well-known strategies from logic
programming. Finally, we use BloomL to develop several practical
distributed programs, including a key-value store similar to Amazon
Dynamo, and show how BloomL encourages the safe composition
of small, easy-to-analyze lattices into larger programs.

Categories and Subject Descriptors
D.3.2 [Language Classiﬁcations]: Concurrent, distributed, and par-
allel languages

General Terms
Design, Languages

Keywords
Bloom, distributed programming, eventual consistency, lattice

1.

INTRODUCTION

As cloud computing becomes increasingly common, the inherent
diﬃculties of distributed programming—asynchrony, concurrency,
and partial failure—aﬀect a growing segment of the developer com-
munity. Traditionally, transactions and other forms of strong consis-
tency encapsulated these problems at the data management layer. But

Permission to make digital or hard copies of all or part of this work for
personal or classroom use is granted without fee provided that copies are
not made or distributed for proﬁt or commercial advantage and that copies
bear this notice and the full citation on the ﬁrst page. To copy otherwise, to
republish, to post on servers or to redistribute to lists, requires prior speciﬁc
permission and/or a fee.
SOCC’12, October 14-17, 2012, San Jose, CA USA
Copyright 2012 ACM 978-1-4503-1761-0/12/10 ...$15.00.

in recent years there has been interest in achieving application-level
consistency criteria without incurring the latency and availability
costs of strongly consistent storage [8, 19].

Two diﬀerent frameworks for these techniques have received
signiﬁcant attention in recent research: Convergent Modules and
Monotonic Logic.

Convergent Modules: In this approach, a programmer writes encap-
sulated modules whose public methods provide certain guarantees
regarding message reordering and retry. For example, Statebox is an
open-source library that merges conﬂicting updates to data items in
a key-value store; the user of the library need only register “merge
functions” that are commutative, associative, and idempotent [21].
This approach has roots in database and systems research [14, 16,
19, 29, 41] as well as groupware [13, 39]. Shapiro et al. recently
proposed a formalism for these approaches called Convergent Repli-
cated Data Types (CvRDTs), which casts these ideas into the alge-
braic framework of semilattices [36, 37].

CvRDTs present two main problems: (a) the programmer bears
responsibility for ensuring lattice properties for their methods (com-
mutativity, associativity, idempotence), and (b) CvRDTs only pro-
vide guarantees for individual values, not for application logic in
general. As an example of this second point, consider the following:
Example 1. A replicated, fault-tolerant courseware application
assigns students into study teams. It uses two set CvRDTs: one for
Students and another for Teams. The application reads a version of
Students and inserts the derived element <Alice,Bob> into Teams.
Concurrently, Bob is removed from Students by another application
replica. The use of CvRDTs ensures that all replicas will eventually
agree that Bob is absent from Students, but this is not enough:
application-level state is inconsistent unless the derived values in
Teams are updated consistently to reﬂect Bob’s removal. This is
outside the scope of CvRDT guarantees.

Taken together, the problems with Convergent Modules present
a scope dilemma: a small module (e.g., a set) makes lattice prop-
erties easy to inspect and test, but provides only simple semantic
guarantees. Large CvRDTs (e.g., an eventually consistent shopping
cart) provide higher-level application guarantees but require the
programmer to ensure lattice properties hold for a complex module,
resulting in software that is diﬃcult to test, maintain, and trust.

Monotonic Logic: In recent work, we observed that the database
theory literature on monotonic logic provides a powerful lens for
reasoning about distributed consistency. Intuitively, a monotonic
program makes forward progress over time: it never “retracts” an
earlier conclusion in the face of new information. We proposed the
CALM theorem, which established that all monotonic programs
are conﬂuent (invariant to message reordering and retry) and hence
eventually consistent [5, 20, 27]. Monotonicity of a Datalog program

is straightforward to determine conservatively from syntax, so the
CALM theorem provides the basis for a simple analysis of the
consistency of distributed programs. We concretized CALM into
an analysis procedure for Bloom, a Datalog-based language for
distributed programming [2, 9].

The original formulation of CALM and Bloom only veriﬁed
the consistency of programs that compute sets of facts that grow
over time (“set monotonicity”); that is, “forward progress” was
deﬁned according to set containment. As a practical matter, this is
overly conservative: it precludes the use of common monotonically
increasing constructs such as timestamps and sequence numbers.

Example 2. In a quorum voting service, a coordinator counts
the number of votes received from participant nodes; quorum is
reached once the number of votes exceeds a threshold. This is clearly
monotonic: the vote counter increases monotonically, as does the
threshold test (count(votes) > k) which “grows” from False to
True. But both of these constructs (upward-moving mutable vari-
ables and aggregates) are labeled non-monotonic by the original
CALM analysis.

The CALM theorem obviates any scoping concerns for conver-
gent monotonic logic, but it presents a type dilemma. Sets are the
only data type amenable to CALM analysis, but the programmer
may have a more natural representation of a monotonically growing
phenomenon. For example, a monotonic counter is more naturally
represented as a growing integer than a growing set. This dilemma
leads either to false negatives in CALM analysis and over-use of
coordination, or to idiosyncratic set-based implementations that can
be hard to read and maintain.

1.1 BloomL: Logic And Lattices

We address the two dilemmas above with BloomL, an extension to
Bloom that incorporates a semilattice construct similar to CvRDTs.
We present this construct in detail below, but the intuition is that
BloomL programs can be deﬁned over arbitrary types—not just sets—
as long as they have commutative, associative, and idempotent merge
functions (“least upper bound”) for pairs of items. Such a merge
function deﬁnes a partial order for its type. This generalizes Bloom
(and traditional Datalog), which assumes a ﬁxed merge function (set
union) and partial order (set containment).

BloomL provides three main improvements in the state of the art

of both Bloom and CvRDTs:

1. BloomL solves the type dilemma of logic programming: CALM
analysis in BloomL can assess monotonicity for arbitrary lat-
tices, making it signiﬁcantly more liberal in its ability to test
for conﬂuence. BloomL can validate the coordination-free use
of common constructs like timestamps and sequence numbers.

2. BloomL solves the scope dilemma of CvRDTs by providing
monotonicity-preserving mappings between lattices via mor-
phisms and monotone functions. Using these mappings, the
per-component monotonicity guarantees oﬀered by CvRDTs
can be extended across multiple items of lattice type. This
capability is key to the CALM analysis described above. It is
also useful for proving the monotonicity of sub-programs even
when the whole program is not designed to be monotonic.

3. For eﬃcient incremental execution, we extend the standard
Datalog semi-naive evaluation scheme [7] to support lattices.
We also describe how to extend an existing Datalog runtime
to support lattices with relatively minor changes.

1.2 Outline

The remainder of the paper proceeds as follows. Section 2 pro-
vides background on Bloom and CALM. In Section 3 we introduce
BloomL, including cross-lattice morphisms and monotone functions.
We detail BloomL’s built-in lattice types and show how developers
can deﬁne new lattices. We also describe how the CALM analysis
extends to BloomL. In Section 4, we describe how we modiﬁed the
Bloom runtime to support BloomL.

In Sections 5 and 6, we present two case studies. First, we use
BloomL to implement a distributed key-value store that supports
eventual consistency, object versioning using vector clocks, and quo-
rum replication. Second, we revisit the simple e-commerce scenario
presented by Alvaro et al. in which clients interact with a replicated
shopping cart service [2]. We show how BloomL can be used to
make the “checkout” operation monotonic and conﬂuent, despite
the fact that it requires aggregation over a distributed data set.

2. BACKGROUND

In this section, we review the Bloom programming language and
the CALM program analysis. We present a simple program for
which the CALM analysis over sets yields unsatisfactory results.

2.1 Bloom

Bloom programs are bundles of declarative statements about col-
lections of facts (tuples). An instance of a Bloom program performs
computation by evaluating its statements over the contents of its
local database. Instances communicate via asynchronous messaging.
An instance of a Bloom program proceeds through a series of
timesteps, each containing three phases.1 In the ﬁrst phase, inbound
events (e.g., network messages) are received and represented as
facts in collections. In the second phase, the program’s statements
are evaluated over local state to compute all the additional facts
that can be derived from the current collection contents. In some
cases (described below), a derived fact is intended to achieve a “side
eﬀect,” such as modifying local state or sending a network message.
These eﬀects are deferred during the second phase of the timestep;
the third phase is devoted to carrying them out.

The initial implementation of Bloom, called Bud, allows Bloom
logic to be embedded inside a Ruby program. Figure 1 shows a
Bloom program represented as an annotated Ruby class. A small
amount of Ruby code is needed to instantiate the Bloom program
and begin executing it; more details are available on the Bloom
language website [9].

2.1.1 Data Model

The Bloom data model is based on collections. A collection is
an unordered set of facts, akin to a relation in Datalog. The Bud
prototype adopts the Ruby type system rather than inventing its own;
hence, a fact in Bud is just an array of immutable Ruby objects.
Each collection has a schema, which declares the structure (column
names) of the facts in the collection. A subset of the columns in a
collection form its key: as in the relational model, the key columns
functionally determine the remaining columns. The collections used
by a Bloom program are declared in a state block. For example,
line 5 of Figure 1 declares a collection named link with three
columns, two of which form the collection’s key. Ruby is a dynami-
cally typed language, so keys and values in Bud can hold arbitrary
Ruby objects.

Bloom provides several collection types to represent diﬀerent
kinds of state (Table 1). A table stores persistent data: if a fact

1There is a declarative semantics for Bloom [1, 4], but for the sake
of exposition we describe the language operationally here.

1
2

4
5
6
7
8

10
11
12
13
14

16
17
18

class ShortestPaths

include Bud

state do

table :link, [:from, :to] => [:cost]
scratch :path, [:from, :to, :next_hop, :cost]
scratch :min_cost, [:from, :to] => [:cost]

end

bloom do

path <= link {|l| [l.from, l.to, l.to, l.cost]}
path <= (link*path).pairs(:to => :from) do |l,p|

[l.from, p.to, l.to, l.cost + p.cost]

end

min_cost <= path.group([:from, :to], min(:cost))

end

end

Figure 1: All-pairs shortest paths in Bloom.

appears in a table, it remains in the table in future timesteps (unless
it is explicitly removed). A scratch contains transient data—the
content of scratch collections is emptied at the start of each timestep.
Scratches are akin to SQL views: they are often useful as a way to
name intermediate results or as a “macro” construct to enable code
reuse. A channel allows communication between Bloom instances.
The schema of a channel has a distinguished location speciﬁer
column (preﬁxed with “@”). When a fact is derived for a channel
collection, it is sent to the remote Bloom instance at the address
given by the location speciﬁer.

2.1.2

Statements

Each Bloom statement has one or more input collections and a

single output collection. A statement takes the form:

<collection-identiﬁer> <op> <collection-expression>
The left-hand side (lhs) is the name of the output collection and the
right-hand side (rhs) is an expression that produces a collection. A
statement deﬁnes how the input collections are transformed before
being included (via set union) in the output collection. Bloom al-
lows the usual relational operators to be used on the rhs (selection,
projection, join, grouping, aggregation, and negation), although it
adopts a syntax intended to be more familiar to imperative pro-
grammers. In Figure 1, line 11 demonstrates projection, lines 12–14
perform a join between link and path using the join predicate
link.to = path.from followed by a projection to four attributes,
and line 16 shows grouping and aggregation. Bloom statements
appear in one or more bloom blocks, which group together semanti-
cally related statements to aid readability.

Bloom provides several operators that determine when the rhs
will be merged into the lhs (Table 2). The <= operator performs
standard logical deduction: that is, the lhs and rhs are true at the
same timestep. The <+ and <- operators indicate that facts will be
added to or removed from the lhs collection at the beginning of the
next timestep. The <~ operator speciﬁes that the rhs will be merged
into the lhs collection at some non-deterministic future time. The
lhs of a statement that uses <~ must be a channel; the <~ operator
captures asynchronous messaging.

Bloom allows recursion—i.e., the rhs of a statement can reference
the lhs collection, either directly or indirectly. As in Datalog, certain
constraints must be adopted to ensure that programs with recursive
statements have a sensible interpretation. For deductive statements
(<= operator), we require that programs be syntactically stratiﬁed [6]:
cycles through negation or aggregation are not allowed [4].

Behavior
Name
table
Persistent storage.
scratch Transient storage.
channel Asynchronous communication. A fact derived
into a channel appears in the database of a
remote Bloom instance at a non-deterministic
future time.

Table 1: Bloom collection types.

Op Name
<= merge

<+

<-

<~

deferred merge

deferred delete

async merge

Meaning
lhs includes the content of rhs in the
current timestep.
lhs will include the content of rhs in
the next timestep.
lhs will not include the content of rhs
in the next timestep.
(Remote) lhs will include the content
of the rhs at some non-deterministic
future timestep.

Table 2: Bloom operators.

2.2 CALM Analysis

Work on deductive databases has long drawn a distinction be-
tween monotonic and non-monotonic logic programs. Intuitively, a
monotonic program only computes more information over time—it
never “retracts” a previous conclusion in the face of new evidence.
In Bloom (and Datalog), a simple conservative test for monotonic-
ity is based on program syntax: selection, projection, and join are
monotonic, while aggregation, negation, and deletion are not.

The CALM theorem connects the theory of monotonic logic
with the practical problem of distributed consistency [2, 20]. All
monotonic programs are “eventually consistent” or conﬂuent: for
any given input, all program executions result in the same ﬁnal state
regardless of network non-determinism [5, 27]. Hence, monotonic
logic is a useful building block for loosely consistent distributed
programming.

According to the CALM theorem, distributed inconsistency may
only occur at a point of order: a program location where an asyn-
chronously derived value is consumed by a non-monotonic oper-
ator [2]. This is because asynchronous messaging results in non-
deterministic arrival order, and non-monotonic operators may pro-
duce diﬀerent conclusions when evaluated over diﬀerent subsets of
their inputs. For example, consider a Bloom program consisting of a
pair of collections A and B (both fed by asynchronous channels) and
a rule that sends a message whenever an element of A arrives that is
not in B. This program is non-monotonic and exhibits non-conﬂuent
behavior: the messages sent by the program will depend on the order
in which the elements of A and B arrive.

We have implemented a conservative static program analysis in
Bloom that follows directly from the CALM theorem. Programs that
are free from non-monotonic constructs are “blessed” as conﬂuent:
producing the same output on diﬀerent runs or converging to the
same state on multiple distributed replicas. Otherwise, programs
are ﬂagged as potentially inconsistent. To achieve consistency, the
programmer either needs to rewrite their program to avoid the use
of non-monotonicity or introduce a coordination protocol to ensure
that a consistent ordering is agreed upon at each of the program’s
points of order. Coordination protocols increase latency and reduce
availability in the event of network partitions, so in this paper we
focus on coordination-free designs—that is, monotonic programs.

1
2

4
5

7
8
9
10
11
12

14
15
16
17
18
19

QUORUM_SIZE = 5
RESULT_ADDR = "example.org"

class QuorumVote
include Bud

state do

channel :vote_chn, [:@addr, :voter_id]
channel :result_chn, [:@addr]
table
scratch :cnt, [] => [:cnt]

:votes, [:voter_id]

end

bloom do
votes
cnt
result_chn <~ cnt {|c| [RESULT_ADDR] if c >= QUORUM_SIZE}

<= vote_chn {|v| [v.voter_id]}
<= votes.group(nil, count(:voter_id))

end

end

Figure 2: A non-monotonic Bloom program that waits for a
quorum of votes to be received.

2.2.1 Limitations Of Set Monotonicity

The original formulation of the CALM theorem considered only
programs that compute more facts over time—that is, programs
whose sets grow monotonically. Many distributed protocols make
progress over time but their notion of “progress” is often diﬃcult
to represent as a growing set of facts. For example, consider the
Bloom program in Figure 2. This program receives votes from one
or more clients (not shown) via the vote_chn channel. Once at
least QUORUM_SIZE votes have been received, a message is sent to a
remote node to indicate that quorum has been reached (line 17). This
program resembles a “quorum vote” subroutine that might be used
by an implementation of Paxos [24] or quorum replication [18].

Intuitively, this program makes progress in a semantically mono-
tonic fashion: the set of received votes grows and the size of the
votes collection can only increase, so once a quorum has been
reached it will never be retracted. Unfortunately, the current CALM
analysis would regard this program as non-monotonic because it
contains a point of order: the grouping operation on line 16.

To solve this problem, we need to introduce a notion of program
values that “grow” according to a partial order other than set con-
tainment. We do this by extending Bloom to operate over arbitrary
lattices rather than just the set lattice.

3. ADDING LATTICES TO BLOOM

This section introduces BloomL, an extension to Bloom that al-
lows monotonic programs to be written using arbitrary lattices. We
begin by reviewing the algebraic properties of lattices, monotone
functions, and morphisms. We then introduce the basic concepts of
BloomL and detail the built-in lattices provided by the language. We
also show how users can deﬁne their own lattice types.

When designing BloomL, we decided to extend Bloom to in-
clude support for lattices rather than building a new language from
scratch. Hence, BloomL is backward compatible with Bloom and
was implemented with relatively minor changes to the Bud runtime.
We describe how code written using lattices can interoperate with
traditional Bloom collections in Section 3.5.

3.1 Deﬁnitions

A bounded join semilattice is a triple (cid:104)S , (cid:116), ⊥(cid:105), where S is a set,
(cid:116) is a binary operator (called “join” or “least upper bound”), and ⊥
is an element of S (called “bottom”). The (cid:116) operator is associative,
commutative, and idempotent. The (cid:116) operator induces a partial order

1
2

4
5

7
8
9
10
11
12
13

15
16
17
18
19
20
21

QUORUM_SIZE = 5
RESULT_ADDR = "example.org"

class QuorumVoteL

include Bud

state do

channel :vote_chn, [:@addr, :voter_id]
channel :result_chn, [:@addr]
lset
lmax
lbool

:votes
:cnt
:quorum_done

end

bloom do
<= vote_chn {|v| v.voter_id}
votes
cnt
<= votes.size
quorum_done <= cnt.gt_eq(QUORUM_SIZE)
result_chn <~ quorum_done.when_true { [RESULT_ADDR] }

end

end

Figure 3: A monotonic BloomL program that waits for a quo-
rum of votes to be received.

≤S on the elements of S : x ≤S y if x(cid:116)y = y. Note that although ≤S is
only a partial order, the least upper bound is deﬁned for all elements
x, y ∈ S . The distinguished element ⊥ is the smallest element in S :
x (cid:116) ⊥ = x for every x ∈ S . For brevity, we use the term “lattice” to
mean “bounded join semilattice” in the rest of this paper. We use
the informal term “merge function” to mean “least upper bound.”

A monotone function is a function f : S → T such that S , T are
partially ordered sets (posets) and ∀a, b ∈ S : a ≤S b ⇒ f (a) ≤T
f (b). That is, f maps elements of S to elements of T in a manner
that respects the partial orders of both posets.2

A morphism from lattice (cid:104)X, (cid:116)X, ⊥X(cid:105) to lattice (cid:104)Y, (cid:116)Y , ⊥Y (cid:105) is a
function g : X → Y such that g(⊥X) = ⊥Y and ∀a, b ∈ X : g(a (cid:116)X
b) = g(a) (cid:116)Y g(b). Intuitively, g maps elements of X to elements of
Y in a way that preserves the lattice properties. Note that morphisms
are monotone functions but the converse is not true in general.

3.2 Language Constructs

BloomL allows both lattices and collections to represent state. A
lattice is analogous to a collection type in Bloom, while a lattice
element corresponds to a particular collection. For example, the
lset lattice is similar to the table collection type provided by
Bloom; an element of the lset lattice is a particular set. In the
terminology of object-oriented programming, a lattice is a class that
obeys a certain interface and an element of a lattice is an instance of
that class. Figure 3 contains an example BloomL program.

As with collections, the lattices used by a BloomL program are
declared in a state block. More precisely, a state block declaration
introduces an identiﬁer that is associated with a lattice element; over
time, the binding between identiﬁers and lattice elements is updated
to reﬂect state changes in the program. For example, line 10 of
Figure 3 declares an identiﬁer votes that is mapped to an element
of the lset lattice. As more votes are received, the lattice element
associated with the votes identiﬁer changes (it moves “upward” in
the lset lattice). When a lattice identiﬁer is declared, it is initially
bound to ⊥, the smallest element in the lattice. For example, an
lset lattice initially contains the empty set.

2To simplify the presentation, these deﬁnitions assume that mono-
tone functions and morphisms are unary. BloomL supports monotone
functions and morphisms with any number of arguments.

Least element (⊥) Merge(a, b) Morphisms
a ∨ b
false

when_true(&blk) → v

Monotone functions

Name
lbool

lmax

Description
Boolean lattice
(false → true)
Max over an
ordered domain

lmin

Min over an
ordered domain

−∞

∞

max(a, b)

min(a, b)

lset

Set of values

empty set

a ∪ b

lpset

Set of non-
negative numbers

empty set

a ∪ b

lbag

Multiset of values

empty multiset

a ∪ b

lmap

Map from keys to
lattice values

empty map

see text

gt(n) → lbool
gt_eq(n) → lbool
+(n) → lmax
−(n) → lmax
lt(n) → lbool
lt_eq(n) → lbool
+(n) → lmin
−(n) → lmin
intersect(lset) → lset
project(&blk) → lset
product(lset) → lset
contains?(v) → lbool
intersect(lpset) → lpset
project(&blk) → lpset
product(lpset) → lpset
contains?(v) → lbool
intersect(lbag) → lbag
project(&blk) → lbag
multiplicity(v) → lmax
contains?(v) → lbool
+(lbag) → lbag
intersect(lmap) → lmap
project(&blk) → lmap
key_set() → lset
at(v) → any-lattice
key?(v) → lbool

size() → lmax

size() → lmax
sum() → lmax

size() → lmax

size() → lmax

Table 3: Built-in lattices in BloomL. Note that v denotes a Ruby value, n denotes a number, and blk indicates a Ruby code block
(anonymous function).

3.2.1

Statements

Statements take the same form in both Bloom and BloomL:

<identiﬁer> <op> <expression>

The identiﬁer on the lhs can refer to either a set-oriented collection
or a lattice element. The expression on the rhs can contain both
traditional relational operators (applied to Bloom collections) and
methods invoked on lattices. Lattice methods are similar to methods
in an object-oriented language and are invoked using the standard
Ruby method invocation syntax. For example, line 17 of Figure 3
invokes the size method on an element of the lset lattice.

If the lhs is a lattice, the statement’s operator must be either <= or
<+ (instantaneous or deferred deduction, respectively). The meaning
of these operators is that, at either the current or the following
timestep, the lhs identiﬁer will take on the result of applying the
lattice’s least upper bound to the lhs and rhs lattice elements. The
intuition remains the same as in Bloom: the rhs value is “merged
into” the lhs lattice, except that the semantics of the merge operation
are deﬁned by the lattice’s least upper bound operator. We require
that the lhs and rhs refer to a lattice of the same type.

BloomL does not support deletion (<- operator) for lattices. Lat-
tices do not directly support asynchronous communication (via the
<~ operator) but lattice elements can be embedded into facts that
appear in channels (Section 3.5.2).

3.2.2 Lattice Methods

BloomL statements compute values over lattices by invoking
methods on lattice elements. Just as a subset of the relational algebra
is monotonic, some lattice methods are monotone functions (as
deﬁned in Section 3.1). A monotone lattice method guarantees that,
if the lattice on which the method is invoked grows (according to
the lattice’s partial order), the value returned by the method will
grow (according to the return value’s lattice type). For example, the

size method provided by the lset lattice is monotone because
as more elements are added to the set, the size of the set increases.
Intuitively, a lattice’s monotone methods constitute a “safe” interface
of operations that can be invoked in a distributed setting without
risk of inconsistency.

A lattice method’s signature indicates its monotonicity properties.
BloomL distinguishes between methods that are monotone and a
subset of monotone methods that are morphisms. Section 3.1 deﬁnes
the properties that a morphism must satisfy, but the intuition is that
a morphism on lattice T can be distributed over T ’s least upper
bound. For example, the size method of the lset lattice is not
a morphism. To see why, consider two elements of the lset lat-
tice, {1, 2} and {2, 3}. The size method is not a morphism because
size({1, 2} (cid:116)lset {2, 3}) (cid:44) size({1, 2}) (cid:116)lmax size({2, 3}). Morphisms
can be evaluated more eﬃciently than monotone methods, as we
discuss in Section 4.1.

Lattices can also deﬁne non-monotonic methods. Using a non-
monotonic lattice method is analogous to using a non-monotonic
relational operator in Bloom: the Bud interpreter stratiﬁes the pro-
gram to ensure that the input value is computed to completion before
allowing the non-monotonic method to be invoked. BloomL encour-
ages developers to minimize the use of non-monotonic constructs:
as the CALM analysis suggests, non-monotonic reasoning may need
to be augmented with coordination to ensure consistent results.

Every lattice deﬁnes a non-monotonic reveal method that re-
turns a representation of the lattice element as a plain Ruby value.
For example, the reveal method on an lmax lattice returns a Ruby
integer. This method is non-monotonic because once the underly-
ing Ruby value has been extracted from the lattice, BloomL cannot
ensure that subsequent code uses the value in a monotonic fashion.

3.3 Built-in Lattices

Table 3 lists the lattices included with BloomL. The built-in lat-
tices provide support for several common notions of “progress”: a
predicate that moves from false to true (lbool), a numeric value
that strictly increases or strictly decreases (lmax and lmin, respec-
tively), and various kinds of collections that grow over time (lset,
lpset, lbag, and lmap). The behavior of most of the lattice meth-
ods should be unsurprising, so we do not describe every method in
this section.

The lbool lattice represents conditions that, once satisﬁed, re-
main satisﬁed. For example, the gt morphism on the lmax lattice
takes a numeric argument n and returns an lbool; once the lmax
exceeds n, it will remain > n. The when_true morphism takes a
Ruby block; if the lbool element has the value true, when_true
returns the result of evaluating the block. For example, see line 19
in Figure 3. when_true is similar to an “if” statement.3

The collection-like lattices support familiar operations such as
union, intersection, and testing for the presence of an element in the
collection. The project morphism takes a code block and forms a
new collection by applying the code block to each element of the
input collection. Elements for which the code block returns nil are
omitted from the output collection, which allows project to be
used as a ﬁlter.

The lbag lattice demonstrates how BloomL can support multisets.
Note that the lbag merge function takes the maximum of the multi-
plicities of an element that appears in both input lattices. Although
this is the standard deﬁnition of multiset union, some applications
might ﬁnd summing the element multiplicities to be more useful.
However, this behavior would not be a valid least upper bound
(because it is not idempotent). Instead, applications that need to
compute the multiset sum can use the + morphism.

The lpset lattice is an example of how BloomL can be used
to encode domain-speciﬁc knowledge about an application. If the
developer knows that a set will only contain non-negative numbers,
the sum of those numbers increases monotonically as the set grows.
Hence, sum is a monotone function of lpset; in contrast, taking the
sum of the elements of an lset is non-monotonic in general.

The lmap lattice associates keys with values. Keys are immutable
Ruby objects and values are lattice elements. For example, a web
application could use an lmap to associate session IDs with an
lset containing the pages visited by that session. The lmap merge
function takes the union of the key sets of its input maps. If a key
occurs in both inputs, the two corresponding values are merged
using the appropriate lattice merge function. Note that the at(v)
morphism returns the lattice element associated with key v (or ⊥ if
the lmap does not contain v).

3.4 User-deﬁned Lattices

The built-in lattices are suﬃcient to express many programs. How-
ever, BloomL also allows developers to create custom lattices to
capture domain-speciﬁc behavior. To deﬁne a new lattice, a devel-
oper creates a Ruby class that meets a certain API contract. Figure 4
shows a simple implementation of the lset lattice using a Ruby
array for storage.4

A lattice class must inherit from the built-in Bud::Lattice class

and must also deﬁne two methods:

• initialize(i): given a Ruby object i, this method con-
structs a new lattice element that “wraps” i (this is the stan-

3Observe that an “else” clause would test for an upper bound on the
ﬁnal lattice value, which is a non-monotonic property.
4We omit a few lset methods for brevity. While we use an array for
simplicity, this is ineﬃcient (e.g., duplicate elimination is expensive).
The built-in lset implementation uses a hash-based set data type.

1
2

4
5
6

8
9
10

12
13
14

16
17
18

20
21
22
23

class Bud::SetLattice < Bud::Lattice

wrapper_name :lset

def initialize(x=[])

@v = x.uniq # Remove duplicates from input

end

def merge(i)

self.class.new(@v | i.reveal)

end

morph :intersect do |i|

self.class.new(@v & i.reveal)

end

morph :contains? do |i|

Bud::BoolLattice.new(@v.member? i)

end

monotone :size do

Bud::MaxLattice.new(@v.size)

end

end

Figure 4: Example implementation of the lset lattice.

dard Ruby syntax for deﬁning a constructor). If i is nil (the
null reference), this method returns ⊥.

• merge(e): given a lattice element e, this method returns the
least upper bound of e and self. The programmer must ensure
that this method satisﬁes the algebraic properties of least up-
per bound—in particular, it must be commutative, associative,
and idempotent (Section 3.1). Note that e and self must be
instances of the same class.

Lattices can also deﬁne any number of monotone functions, mor-
phisms, and non-monotonic methods. The syntax for declaring mor-
phisms and monotone functions can be seen in lines 12–14 and
20–22 of Figure 4, respectively. Note that lattice elements are im-
mutable—that is, lattice methods (including merge methods) must
return new values, rather than modifying any of their inputs.

A lattice deﬁnition must specify a keyword that can be used in
BloomL state blocks. This is done using the wrapper_name class
method. For example, line 2 of Figure 4 means that “lset :foo”
in a state block will introduce an identiﬁer foo that is associated
with an instance of Bud::SetLattice.

3.5

Integration With Set-oriented Logic
BloomL provides two features to ease integration of lattice-based

code with Bloom rules that use set-oriented collections.

3.5.1 Converting Collections Into Lattices

This feature enables an intuitive syntax for merging the contents
of a set-oriented collection into a lattice. If a statement has a Bloom
collection on the rhs and a lattice on the lhs, the collection is con-
verted into a lattice element by “folding” the lattice’s merge function
over the collection. That is, each element of the collection is con-
verted to a lattice element (by invoking the lattice constructor) and
then the resulting lattice elements are merged together via repeated
application of the lattice’s merge method. In our experience, this is
usually the behavior intended by the user.

For example, line 16 of Figure 3 contains a Bloom collection on
the rhs and an lset lattice on the lhs. This statement is evaluated by
constructing a singleton lset for each fact in the rhs collection and
then merging the sets together. The resulting lset is then merged
with the votes lattice referenced by the lhs.

3.5.2 Embedding Lattice Values In Collections

BloomL allows lattice elements to be used as column values of
facts in Bloom collections. This feature allows BloomL programs
to use a mixture of Bloom-style relational operators and lattice
method invocations, depending on which is more convenient. Bloom
also provides several collection types with special semantics (e.g.,
network communication, durable storage); allowing lattice elements
to be embedded into collections avoids the need to create a redundant
set of facilities for lattices.

Consider a simple BloomL statement that derives facts with an

embedded lattice element as a column:

t1 <= t2 {|t| [t.x, cnt]}

where t1 and t2 are collections, cnt is a lattice, and the key of t1
is its ﬁrst column. Note that cnt might change over the course of
a single timestep (speciﬁcally, cnt can increase according to the
lattice’s partial order). This might result in deriving multiple t1 facts
that diﬀer only in the second column, which would violate t1’s key.
To resolve this situation, BloomL allows multiple facts to be
derived that diﬀer only in their embedded lattice values; those facts
are merged into a single fact using the lattice’s merge function. This
is similar to specifying a procedure for how to resolve key constraint
violations, a feature supported by some databases [30, 38]. For
similar reasons, lattice elements cannot be used as keys in Bloom
collections.

3.6 CALM Analysis For Lattices

As discussed in Section 2.2, CALM-based program analysis de-
termines whether a program is order-sensitive by looking for “points
of order”—locations where an asynchronously computed value is
consumed by a non-monotonic operator. BloomL simply expands
the set of monotonic operations that a program can contain; hence,
we did not need to make any fundamental changes to our program
analysis. Instead, we simply replaced the hard-coded list of mono-
tonic operations with a list of the monotonic methods deﬁned by the
lattices used by the current program. In Sections 5 and 6, we show
how CALM analysis can be applied to several BloomL programs.

CALM analysis is grounded in a model-theoretic characterization
of conﬂuence [27]. This work was done in the context of Dedalus,
the formal language on which Bloom is based [4]. These results
apply directly to Bloom, whose semantics are grounded in those of
Dedalus. Monotonicity analysis in BloomL is a natural extension of
the work on Bloom, but the development of a formal model-theoretic
semantics for BloomL remains a topic for future work.

4.

IMPLEMENTATION

In this section, we describe how to evaluate BloomL programs.
First, we generalize semi-naive evaluation to support lattices. We
validate that our implementation of semi-naive evaluation results in
signiﬁcant performance gains and is competitive with the traditional
set-only semi-naive evaluation scheme in Bud. We also describe how
we extended Bud to support BloomL with relatively few changes.

4.1 Evaluation Strategy

Naive evaluation is a simple but ineﬃcient approach to evaluating
recursive Datalog programs. Evaluation proceeds in rounds. In each
round, every rule in the program is evaluated over the entire database,
including all derivations made in previous rounds. This process
stops when a round makes no new derivations. Naive evaluation is
ineﬃcient because it makes many redundant derivations: once a fact
has been derived in round i, it is rederived in every round > i.

Semi-naive evaluation improves upon naive evaluation by making
fewer redundant derivations [7]. Let ∆0 represent the initial database

Figure 5: Performance of three diﬀerent methods for comput-
ing the transitive closure of a graph.

state. In the ﬁrst round, all the rules are evaluated over ∆0; let ∆1
represent the new facts derived in this round. In the second round,
we only need to compute derivations that depend on ∆1 because
everything that can be derived purely from ∆0 has already been
computed.

A similar evaluation strategy works for BloomL statements that
use lattice morphisms. For a given lattice identiﬁer l, let ∆0
l repre-
sent the lattice element associated with l at the start of the current
timestep. Let ∆r
l represent the new derivations for l that have been
made in evaluation round r. During round one, the program’s state-
ments are evaluated and l is mapped to ∆0
l . In
round two, l is now mapped to ∆1
l and evaluating the program’s
statements yields ∆2
for all
identiﬁers l. The ﬁnal value for l is given by (cid:70)i

= ∆i+1
l . This process continues until ∆i
l
l
∆ j
l .

l ; this computes ∆1

This optimization cannot be used for monotone functions that
are not morphisms. This is because semi-naive evaluation requires
that we apply functions to the partial results derived in each round k
into ∆k
l , and later combine them using the lattice’s merge operation—
eﬀectively distributing the function across the merge. For exam-
ple, consider computing the lset lattice’s size method, which
returns an lmax lattice. The semi-naive strategy would compute
(cid:70)i
lset)—the maximum of the sizes of the incremental
results produced in each round. Thus it produces a diﬀerent result
than naive evaluation, which evaluates the size function against the
complete database state in each round.

lmax: j=0 size(∆ j

l: j=0

Implementing semi-naive style evaluation for lattices was straight-
forward. For each lattice identiﬁer l, we record two values: a “total”
value (the least upper bound of the derivations made for l in all
previous rounds) and a “delta” value (the least upper bound of the
derivations made for l in the last round). We implemented a pro-
gram rewrite that examines each BloomL statement. If a statement
only applies morphisms to lattice elements, the rewrite adjusts the
statement to use the lattice’s delta value rather than its total value.

4.2 Performance Validation

To validate the eﬀectiveness of semi-naive evaluation for BloomL
programs, we wrote two versions of a program to compute the tran-
sitive closure of a directed acyclic graph. One version was written in
Bloom and used Bloom collections. The other version was written
in BloomL using morphisms over the lset lattice. For the BloomL
version, we ran the program both with and without semi-naive eval-
uation enabled. As input, we generated synthetic graphs of various
sizes—in a graph with n nodes, each node had roughly log2 n out-
going edges. We ran the experiment using a 2.13 GHz Intel Core 2

 0 10 20 30 40 50 60 0 50 100 150 200 250Runtime (sec)Graph size (number of paths, 1000s)BloomLattice (Semi-Naive)Lattice (Naive)Duo processor and 4GB of RAM, running Mac OS X 10.7.4 and
Ruby 1.9.3-p194. We ran each program variant ﬁve times on each
graph and report the mean elapsed wall-clock time.

Figure 5 shows how the runtime of each program varied with
the size of the graph. Note that we only report results for the naive
BloomL strategy on small input sizes because this variant ran very
slowly as the graph size increased. The poor performance of naive
evaluation is not surprising: after deriving all paths of length n,
naive evaluation will then rederive all those paths at every subse-
quent round of the ﬁxpoint computation. In contrast, after computing
length n paths, a semi-naive strategy will only generate length n + 1
paths in the next round. Bloom and semi-naive BloomL achieve sim-
ilar results. We instrumented Bud to count the number of derivations
made by the Bloom and semi-naive lattice variants—as expected,
both programs made a similar number of derivations. These re-
sults suggest that our implementation of semi-naive evaluation for
BloomL is eﬀective and performs comparably with a traditional
implementation of semi-naive evaluation for sets.

For large inputs, Bloom began to outperform the semi-naive lattice
variant. We suspect this is because the lattice implementation copies
more data than Bloom does for this benchmark. Lattice elements
are immutable, so the lset merge function allocates a new object
to hold the result of the merge. In contrast, Bloom collections are
modiﬁed in-place. We plan to improve the lattice runtime to avoid
copies when it can determine that in-place updates are safe.

4.3 Discussion

When designing BloomL, we chose to extend the original Bloom
language rather than inventing a new language from scratch. This
design philosophy also applied to our language implementation:
we found we were able to to extend Bud to support BloomL with
relatively minor changes.

Bud initially had about 7300 lines of Ruby source code (LOC).
Adding support for BloomL required less than 1000 lines of new
or modiﬁed code; moreover, most of these changes were cleanly
separated from the core Bud code. For example, the built-in lattice
types constituted 300 LOC and support for lattice-based query plan
elements required 250 LOC. In contrast, we had to make no changes
to Bud’s core ﬁxpoint loop and extending CALM analysis to support
lattices required modifying only 10 LOC. This experience suggests
that support for lattices can be added to an existing Datalog engine
in a relatively straightforward manner.

5. CASE STUDY: KEY-VALUE STORE

The next two sections contain case studies that show how BloomL
can be used to build practical distributed programs.5 Both case
studies are monotonic: that is, both programs consist of monotone
functions applied to lattices. As a result, the BloomL compiler can
verify that both of them are eventually consistent.

In the ﬁrst case study, we show that a distributed, eventually con-
sistent key-value store can be composed via a series of monotonic
mappings between simple lattices. This example shows how BloomL
overcomes the “scope dilemma” of CvRDTs: by composing a com-
plex program from simple lattices (mostly BloomL built-ins), we
can feel conﬁdent that individual lattices are correct, while CALM
analysis ﬁnishes the job of verifying whole-program consistency.

5.1 Basic Architecture

A key-value store (KVS) provides a lookup service that allows
client applications to store and retrieve the value associated with
a given key. Key-value pairs are typically replicated on multiple

5Complete code listings for these case studies are available at
http://db.cs.berkeley.edu/bloom-lattice.

1
2
3
4
5
6
7
8
9
10

1
2
3

5

7
8
9
10
11
12
13

module KvsProtocol

state do

channel :kvput, [:reqid, :@addr] => [:key, :val,

:client_addr]

channel :kvput_resp, [:reqid] => [:@addr, :replica_addr]
channel :kvget, [:reqid, :@addr] => [:key, :client_addr]
channel :kvget_resp, [:reqid] => [:@addr, :val,

:replica_addr]

end

end

Figure 6: Key-value store interface.

class KvsReplica
include Bud
include KvsProtocol

state { lmap :kv_store }

bloom do

<= kvput {|c| {c.key => c.val}}

kv_store
kvput_resp <~ kvput {|c| [c.reqid, c.client_addr, ip_port]}
kvget_resp <~ kvget {|c| [c.reqid, c.client_addr,

kv_store.at(c.key), ip_port]}

end

end

Figure 7: KVS replica implementation in BloomL.

storage nodes for redundancy and the key space is partitioned to
improve aggregate storage and throughput. Eventual consistency is
a common correctness criterion: after all client updates have reached
all storage nodes, all the replicas of a key-value pair will converge
to the same ﬁnal state [41, 43].

Figure 6 shows a simple KVS interface in BloomL. Client applica-
tions initiate get(key) and put(key, val) operations by inserting facts
into the kvget and kvput channels, respectively; server replicas
return responses via the kvget_resp and kvput_resp channels.
Figure 7 contains the BloomL code for a KVS server replica. An
lmap lattice is used to maintain the mapping between keys and
values (line 5). Since the values in an lmap lattice must themselves
be lattice elements, for now we assume that clients only want to
store and retrieve monotonically increasing lattice values; we discuss
how to lift this restriction in Section 5.2. To handle a put(key, val)
request, a new key → val lmap is created and merged into kv_store
(line 8). If kv_store already contains a value for the given key,
the two values will be merged together using the value lattice’s
merge function (see Section 3.3 for details). Observe that we use
the BloomL features described in Section 3.5 to allow traditional
Bloom collections (e.g., channels) and lattices (e.g., the kv_store
lattice) to be used by the same program. Note also that ip_port is
a built-in function that returns the IP address and port number of the
current Bud instance.

The state of two replicas can be synchronized by simply exchang-
ing their kv_store maps; the lmap merge function automatically
resolves conﬂicting updates made to the same key. This property
allows considerable ﬂexibility in how replicas propagate updates.

5.2 Object Versioning

The basic KVS design is suﬃcient for applications that want to
store monotonically increasing values such as session logs or in-
creasing counters. To allow storage of values that change in arbitrary
ways, we now consider how to support object versions. This is a
classic technique for recognizing and resolving mutual inconsis-
tency between members of a distributed system [32]. Our design is
similar to that used by Amazon Dynamo [12].

that is, the built-in least upper bound for an lmap that contains lmax
values is consistent with the partial order given above.7

5.2.2 Dominating Sets

We use a custom lattice type ldom to represent a dominating set.
As discussed above, a dominating set is a set of (cid:104)version, value(cid:105)
pairs; both elements of the pair are themselves represented as lattice
values. In the KVS, the version lattice is a vector clock (that is, an
lmap containing lmax values); the value lattice is whatever value
the user wants to store in the KVS.8

The discussion above suggests a natural merge function for ldom:
given two input ldom elements e and e(cid:48), the merge function omits
all “dominated” pairs. For example, a (cid:104)version, value(cid:105) pair in e is
included in the result of the merge unless there is a pair in e(cid:48) whose
version is strictly greater.

The ldom lattice provides two functions, version and value,
that return the least upper bound of the concurrent versions or values,
respectively. In the KVS, the value function corresponds to recon-
ciling conﬂicting updates, whereas version returns the vector clock
associated with the reconciled value. Note that while the version
of a given ldom increases over time (as new versions are observed),
the value does not; hence, version is a monotone function but
value is not. Since the goal of object versioning is to allow values
to change in non-monotonic ways, this is the expected behavior.

5.2.3 Discussion

Figure 8 shows the lattices used in a KVS with object versioning.
Surprisingly, adding support for object versioning did not require
any changes to the KVS replica code. Instead, clients simply store
ldom values containing a single (cid:104)vector-clock, value(cid:105) pair, incre-
menting their position in the vector clock as described above. The
KVS replica merges these ldom values into an lmap as usual; the
ldom merge function handles conﬂict resolution in the appropriate
manner. Moreover, by composing the KVS from a collection of
simple lattices, we found it easy to reason about the behavior of
the system. For example, convincing ourselves that KVS replicas
will eventually converge only required checking that the individual
ldom, lmap, and lmax lattices satisfy the lattice properties, rather
than analyzing the behavior of the system as a whole.

Our design compares favorably to traditional implementations of
object versioning and vector clocks. For example, the implementa-
tion of vector clocks alone in the Voldemort KVS requires 216 lines
of Java, not including whitespace or comments [25]. In BloomL,
vector clocks follow directly from the composition of the lmap
and lmax lattices, and the entire KVS requires less than 100 lines
of Ruby and BloomL code, including the client library. The ldom
lattice requires an additional 50 lines of Ruby but is completely
generic, and could be included as a built-in lattice.

5.3 Quorum Reads and Writes

To further demonstrate the ﬂexibility of our implementation, we
add an additional feature to our KVS: the ability to submit reads
and writes to a conﬁgurable number of nodes. If a client reads from
R nodes and writes to W nodes in a KVS with N replicas, the user
can set R + W > N to achieve behavior equivalent to a quorum
replication system [18], or use smaller values of R and W if eventual

7The observation that vector time has a lattice structure was made
by Mattern [28].
8If the user stores a value that does not have a natural merge function,
similar systems typically provide a default merge function that
collects conﬂicting updates into a set for eventual manual resolution
by the user. Such a strategy corresponds to using lset as the value
lattice in BloomL.

Figure 8: Lattice structure of a KVS with object versioning.
Rectangles are lattices and ovals are atomic values.

Each replica associates keys with sets of (cid:104)vector-clock, value(cid:105)
pairs. The vector clock captures the causal relationship between
diﬀerent versions of a record [15, 28]. Clients store and retrieve
(cid:104)vector-clock, value(cid:105) pairs. When a client updates a value it has
previously read, the client increments its own position in the vector
clock and includes the updated vector clock VU with its put operation.
Upon receiving an update, the server compares VU with the set of
vector clocks associated with the updated key. For each such vector
clock VS , the server considers three cases:

1. VU > VS : the client’s update happens-after VS , so VS is re-

placed with VU .

2. VU < VS : the client’s update happens-before VS , so VS is

retained.6

3. VU and VS are incomparable: the two versions are concurrent,

so both VU and VS are retained.

By applying these rules, each replica retains a set of mutually con-
current versions for each key. To handle a get operation, the server
returns a single (cid:104)vector-clock, value(cid:105) pair by merging together the
vector clocks and using a user-supplied reconciliation function to
merge together the conﬂicting values, as described below. We call
the set of incomparable version-value pairs a dominating set.

From a BloomL perspective, each replica still stores a monoton-
ically increasing value—the only diﬀerence is that in this scheme,
the version stored by a replica increases over time, rather than the
associated value. Hence, we now consider how to support vector
clocks and dominating sets using BloomL.

5.2.1 Vector Clocks

A vector clock is a map from node identiﬁers to logical clocks [15,
28]. Let Ve denote the vector clock for event e; let Ve(n) denote the
logical clock associated with node n in Ve. If Ve < Ve(cid:48) , e causally
precedes e(cid:48), where

Ve < Ve(cid:48) ≡ ∀x[Ve(x) ≤ Ve(cid:48) (x)] ∧ ∃y[Ve(y) < Ve(cid:48) (y)]

In BloomL, a vector clock can be represented as an lmap that maps
node identiﬁers to lmax values. Each lmax represents the logical
clock of a single node; this is appropriate because the logical clock
value associated with a given node will only increase over time. The
merge function provided by lmap achieves the desired semantics—

6This situation might arise due to duplication and reordering of
messages by the network.

lmapkeyldomlmapnode IDlmaxuser-latticeVector ClockKey-Value StoreDominating Setof <Version, Value> PairsUser-DeﬁnedMerge Function1
2
3
4
5
6
7
8
9
10

12
13

15

17
18
19
20
21
22
23
24
25

27
28
29
30
31
32
33

module CartProtocol

state do

channel :action_msg,

[:@server, :session, :op_id] => [:item, :cnt]

channel :checkout_msg,

[:@server, :session, :op_id] => [:lbound, :addr]

channel :response_msg,

[:@client, :session] => [:summary]

end

end

module MonotoneReplica
include CartProtocol

state { lmap :sessions }

bloom do

sessions <= action_msg do |m|

c = LCart.new({m.op_id => [ACTION, m.item, m.cnt]})
{ m.session => c }

end
sessions <= checkout_msg do |m|

c = LCart.new({m.op_id => [CHECKOUT, m.lbound, m.addr]})
{ m.session => c }

end

response_msg <~ sessions do |session, cart|

cart.is_complete.when_true {

[cart.checkout_addr, session, cart.summary]

}
end

end

end

Figure 10: Cart server replica in BloomL that supports a mono-
tonic (coordination-free) checkout operation.

sponse can be returned to the client. However, observe that the client
knows exactly which add and remove operations should be reﬂected
in the result of the checkout. If that information can be propagated
to the cart service, any server replica can decide if it has enough in-
formation to safely process the checkout operation without needing
additional coordination. This design is monotonic: once a checkout
response is produced, it will never change or be retracted. Our goal
is to translate this design into a monotonic BloomL program.

Figure 10 contains the server code for this design (we omit the
client code for the sake of brevity). Communication with the client
occurs via the channels declared in the CartProtocol module.
Each server replica stores an lmap lattice that associates session
IDs with lcart lattice elements. An lcart is a custom lattice that
represents the state of a single shopping cart. An lcart contains
a set of client operations. Each operation has a unique ID; oper-
ation IDs are assigned by the client in increasing numeric order
without gaps. An lcart contains two kinds of operations, actions
and checkouts. An action describes the addition or removal of k
copies of an item from the cart. An lcart contains at most one
checkout operation—the checkout speciﬁes the smallest operation
ID that must be reﬂected in the result of the checkout, along with
the address where the checkout response should be sent. The lcart
merge function takes the union of the operations in both input carts
(operation IDs ensure idempotence). In Figure 10, lines 19 and 23
construct lcart elements that contain a single action or checkout
operation, respectively. These singleton carts are then merged with
the previous lcart associated with the client’s session, if any.

An lcart is complete if it contains a checkout operation as well
as all the actions in the ID range identiﬁed by the checkout. Hence,
testing whether an lcart is complete is a monotone function: it is
similar to testing whether an accumulating set has crossed a thresh-
old. Hence, if any server replica determines that it has a complete

Figure 9: Shopping cart system architecture.

consistency is suﬃcient. This scheme allows users to vary R and W
on a per-operation basis, depending on their consistency, durability,
and latency requirements.

To support this feature, we can use the BloomL quorum voting
pattern introduced in Figure 3. After sending a write to W systems,
the KVS client accumulates kvput_resp messages into an lset.
Testing for quorum can be done in a monotonic fashion by mapping
the lset to an lmax (using the size method) and then performing a
threshold test using gt_eq on lmax. As expected, this is monotonic:
once quorum has been reached, it will never be retracted.

Quorum reads work similarly except that the client must also
merge together the R versions of the record it receives. This follows
naturally from the discussion in Section 5.2: the client simply takes
the least upper bound of the values it receives, which produces the
expected behavior. The client can optionally write the merged value
back to the KVS (so-called “read repair” [12]); note that the ldom
merge method also updates the record’s vector clock appropriately.

6. CASE STUDY: SHOPPING CARTS

In the previous section, we showed how a complete, consistent
distributed program can be composed via monotonic mappings be-
tween simple lattice types. In this section, we describe how BloomL
overcomes the “type dilemma” of Bloom. In prior work, we intro-
duced a case study in Bloom that seemed to require coordination
because of the use of distributed aggregation [2]. By using custom
lattice types, the BloomL CALM analysis can verify that our revised
design is eventually consistent without need for coordination.

Figure 9 depicts a simple e-commerce system in which clients
interact with a shopping cart service by adding and removing items
over the course of a shopping session. The cart service is replicated
to improve fault tolerance; client requests can be routed to any
server replica. Eventually, a client submits a “checkout” operation,
at which point the cumulative eﬀect of their shopping session should
be summarized and returned to the client. In a practical system, the
result of the checkout operation might be presented to the client for
conﬁrmation or submitted to a payment processor to complete the
e-commerce transaction. This case study is based on the cart system
from Alvaro et al. [2], which was in turn inspired by the discussion
of replicated shopping carts in the Dynamo paper [12].

6.1 Monotonic Checkout

Alvaro et al. argue that processing a checkout request is non-
monotonic because it requires aggregation over an asynchronously
computed data set—in general, coordination might be required to
ensure that all inputs have been received before the checkout re-

ClientCart ReplicaCart ReplicaCart ReplicaPayment GatewayItem Add/RemoveCheckoutRequest/Responsecart, it can send a response to the client without risking inconsis-
tency.9 Because this program contains only monotonic operations,
CALM analysis can verify that this design is consistent without
requiring additional coordination.

Note that the statement that produces a response to the client
(lines 27–31) is contingent on having a complete cart. The monotone
summary method returns a summary of the actions in the cart—
an exception is raised if summary is called on an incomplete cart.
Similarly, attempting to construct an “illegal” lcart instance (e.g.,
an lcart that contains multiple checkout operations or actions that
are outside the ID range speciﬁed by the checkout) also produces an
exception, since this likely indicates a logic error in the program.

6.2 Discussion

This design is possible because a single client has complete knowl-
edge of the shopping actions in its associated session. Hence, there
is no need for additional distributed coordination—the server repli-
cas accumulate knowledge but do not contribute new information
themselves. If multiple clients could operate on a single shopping
cart, some form of coordination between clients would be needed to
ensure a consistent checkout result.

Note that the threshold test for completeness is a crucial part
of this design. Until a cart is complete, its content changes in a
“non-monotonic” fashion as items are added and removed. However,
these non-monotonic changes are hidden inside the lcart type
and are not directly visible to clients. Clients can only observe the
cart’s state once the cart is complete; at that point, the cart state is
immutable and hence will not change in a non-monotonic fashion.
BloomL enables lcart to expose a limited “safe” interface and to
hide transient non-monotonic changes from direct visibility.

7. RELATED WORK

This paper relates to work on concurrency control, distributed

storage, parallel programming, and non-monotonic logic.

Semantics-based concurrency control: The traditional correct-
ness criteria for concurrency control schemes is serializability [31].
However, ensuring serializability can be prohibitively expensive,
for instance when transactions are long-running or the nodes of a
distributed database are connected via an unreliable network. Thus,
many methods have been proposed to allow non-serializable sched-
ules that preserve some semantic notion of correctness. In particular,
several schemes allow users to specify that certain operations can
be commuted with other operations; this enlarges the space of legal
schedules, increasing the potential for concurrency [14, 16, 44].

O’Neil describes a method for supporting “escrow” transactions,
which allow operations that are only commutative when a certain
limited resource is available [29]. For example, credits and debits
to a bank account might only commute if the bank account balance
can be guaranteed to be non-negative. We are currently exploring
how to add support for escrow operations to BloomL.

To support concurrent editing of shared documents, the group-
ware community has studied a family of algorithms known as Oper-
ational Transformations (OT) [13, 39]. Many OT algorithms have
been proposed but the correctness criteria is typically familiar: after
quiescence, all replicas of the document should converge to the
same ﬁnal state, the causal relationship between operations should
be preserved, and the ﬁnal state of the document should reﬂect the
semantic intent of each user’s editing operations [40].

9Without coordination, the client might receive multiple responses
but they will all reﬂect the same cart contents.

Commutativity in distributed systems: Many distributed systems
allow users to specify that certain operations are commutative, as-
sociative, or idempotent. Helland and Campbell observe that using
commutative, associative and idempotent operations is particularly
valuable as systems scale and guaranteeing global serializability
becomes burdensome [19]. Many distributed storage systems allow
users to provide “merge functions” that are used to resolve write-
write conﬂicts between replicas, allowing the system to eventually
reach a consistent state (e.g., [21, 26, 33, 41]).

Principled eventual consistency: Shapiro et al. recently proposed
Conﬂict-free Replicated Data Types (CRDTs), a framework for de-
signing eventually consistent data values [36, 37]. There are two
kinds of CRDTs: “operation-based” types (called CmRDTs) and
“state-based” types (called CvRDTs). BloomL is more closely related
to CvRDTs (a CvRDT must be a semilattice), although the two
CRDT variants are equivalently expressive. CRDTs and BloomL lat-
tice types often use similar design patterns to achieve coordination-
free convergence. Unlike BloomL, the CRDT approach considers the
correctness of replicated values in isolation. This allows CRDTs to
be more easily adapted into standalone libraries (e.g., Statebox [21]).
However, the narrow focus of CRDTs means that, even if a CRDT
is correct, application state may remain inconsistent (Example 1).
Burckhardt et al. advocate using revision diagrams to simplify
the design of eventually consistent distributed programs [10]. A
revision represents a logical replica of system state; revisions can be
forked and joined, which represents creating new (logical) replicas
and merging replicas together, respectively. Revision a can only be
joined to revision b if b is a descendant of the revision that forked a;
this constraint ensures that revision graphs are semilattices. Note that
this use of lattices diﬀers from BloomL: whereas we constrain how
data values can change, Burckhardt et al. constrain how replicas can
synchronize their states. Another diﬀerence is that Burckhardt et al.
allow non-deterministic outcomes, whereas we focus on conﬂuence.
In subsequent work, Burckhardt et al. have also proposed using
abstract data types to encapsulate distributed state [11], although it
is unclear whether their language allows user-deﬁned types.

Parallel programming: Lattices have also been applied to parallel
programming languages. Kuper and Newton recently proposed λpar,
a deterministic parallel variant of the untyped λ-calculus [23]. Their
approach guarantees deterministic program outcomes in the face of
concurrent reads and writes to shared state by restricting reads and
allowing only monotonically increasing writes to shared variables.
Restricted reads in λpar are expressed by supplying a query set of
lattice elements; a read either blocks or returns a unique element
from the query set that is smaller than or equal to the current value
of the shared variable (according to the lattice’s partial order). This
approach to restricting reads is somewhat similar to the use of
threshold tests in BloomL.

Extending monotonicity in deductive databases: Adding non-
monotonic operators to Datalog increases the expressiveness of
the language but introduces signiﬁcant complexities: unrestricted
use of non-monotonicity would allow programs that imply logical
contradictions (e.g., “p if ¬p”). A simple solution is to disallow
recursion through aggregation or negation, which admits only the
class of “stratiﬁed programs” [6]. Many attempts have been made to
assign a semantics to larger classes of programs (e.g., [17, 34, 42]).
In addition to assigning a semantics to programs containing non-
monotonic operators, there has also been research on expanding the
class of operators considered to be monotone. The prior work most
in the spirit of BloomL is by Ross and Sagiv on monotonic aggrega-
tion [35]. Their framework is broader than the term “aggregation”
would suggest. They actually look generally at monotone functions

between partially ordered domains, which conceptually includes
our lattice least upper bounds, monotone functions and morphisms
(though they do not make those distinctions). They extend the notion
of monotone programs to include “growth” by substituting a larger
element in an atom for a smaller one. As we do, they require the
lattice-valued columns to be functionally dependent on the other
attributes in a predicate. One of their main results is that if the target
domain of a monotone function is a complete lattice, then a program
that uses such a function has a unique least ﬁxpoint. While BloomL
has much in common with Ross and Sagiv, there are several diﬀer-
ences. They want to expand the collection of monotone programs
but do not consider conﬂuent distributed programming. In particular,
they do not exploit the idempotence of least upper bound (since
their source domain need not be a lattice), which is important to
us, since it gives conﬂuence with “at-least-once” message delivery.
Also, they do not single out monotone functions that are actually
morphisms. Hence they do not realize the evaluation ﬂexibility we
get from such functions. Finally, they do not propose a practical
programming language or a framework that allows user-deﬁned
lattices to be composed safely.

Köstler et al. investigate deduction in the presence of a partial
ordering of ground atoms, as might be induced by a lattice ordering
on predicate columns [22]. They focus on reduced interpretations
and models, where any atom dominated by another atom is discarded
(unless it belongs to an unbounded maximal chain). One diﬀerence
between their approach and ours is that reduced models need not
satisfy the key dependencies we employ, because a pair of atoms
that agree on a key need not have a common least upper bound.
Köstler et al. construct a complete lattice over equivalence classes of
reduced interpretations. However, the least upper bound of a set of
models in this lattice may be inﬁnite, even if each of those models
is ﬁnite. We suspect our approach and theirs may be isomorphic
when the monotone ordering on atoms is induced by lattice-valued
columns, where the lattices have no inﬁnite chains. However, we
have not rigorously established this relationship yet.

The approach of Zaniolo and Wang [45] to aggregates in LDL++
is quite distinct from that of Ross and Sagiv, and, hence, from ours.
Zaniolo and Wang do not use a lattice as the target domain for an
aggregate or other kind of merge function. Rather, they achieve a
kind of monotonicity by having an aggregate compute a series of
partial results, rather than a single ﬁnal result. With their formulation,
a program computing an average would be judged monotone, where
it would not for us. There are several reasons their treatment is
not suitable for our purposes. For one, they point out that their
programs are not monotone with the inclusion of a predicate for
a ﬁnal result. They do show examples where the partials alone
suﬃce, for example, where the result of an increasing aggregate,
such as sum, is compared to an upper bound. However, we see no
machinery that would automatically distinguish such a use from an
unsafe one, say with average. Further, their use of the choice()
construct to assign an order to a set so an aggregate function can
iterate over it poses two problems for us. One is that they allow
diﬀerent orders to yield diﬀerent aggregate results; this does not ﬁt
with our goal of conﬂuence. More problematic is that in a distributed
computation, choice() would require communication to obtain a
consistent order at diﬀerent nodes, which goes against our desire for
diﬀerent sites to arrive at the same answer without coordination.

commutativity, associativity, and idempotence). CALM analysis ver-
iﬁes that when these modules are composed to form an application,
the complete program satisﬁes the desired consistency properties.
Nevertheless, designing a correct lattice can still be diﬃcult. To
address this, we plan to develop tools to give programmers more
conﬁdence in the correctness of lattice implementations. For ex-
ample, we plan to build a test data generation framework that can
eﬃciently cover the space of possible inputs to lattice merge func-
tions, drawing upon recent work on test generation for Bloom [3].
We also plan to explore a restricted DSL for implementing lattices,
which would make formal veriﬁcation of correctness an easier task.
Eventually consistent designs often consume more resources
over time, requiring periodic “garbage collection” to restore ef-
ﬁciency [36]. Such distributed garbage collection protocols are typi-
cally application-speciﬁc and can be tricky to implement correctly.
We are investigating ways in which BloomL could assist program-
mers in writing garbage collection schemes. For example, a compiler
analysis could verify that the garbage collection protocol does not
change observable program behavior. Garbage collection might also
have a natural representation in lattice-theoretic terms. For example,
a common property is that once an operation has been applied by
all replicas, information required to commute that operation with
concurrent operations can be discarded. In lattice-theoretic terms,
this could be represented by observing that, for a ﬁxed set of replicas,
the greatest lower bound of a lattice among the replicas increases
monotonically; lattice elements that fall below the common greatest
lower bound could be represented more eﬃciently.

In this paper, we have focused on programming with monotoni-
cally increasing values. In fact, many distributed programs feature
values that increase monotonically for a period but then become
immutable. For example, the lcart lattice described in Section 6
accumulates updates but then eventually becomes “complete” and
stops changing. Once a value is immutable, any function can safely
be applied to it (whether monotone or not) without risking inconsis-
tency. The lcart (and lbool) lattices demonstrate that BloomL can
represent such “monotonic-then-immutable” values, but we suspect
that supporting immutability more directly might be useful. For
example, a compiler analysis proving that a value is immutable in
a certain situation would allow non-monotonic functions to safely
be applied to it. Some immutable values can also be represented
more eﬃciently: for example, a complete lcart need only store the
“summarized” cart state, not the log of client operations.

9. CONCLUSION

In this paper, we proposed BloomL, a distributed variant of Data-
log that extends logic programming with join semilattices. BloomL
is particularly valuable for enabling coordination-free, consistent dis-
tributed programming, overcoming key hurdles in prior work. Like
CvRDTs, BloomL allows application-speciﬁc notions of “progress”
to be represented as lattices and goes further by enabling safe map-
pings between lattices. BloomL improves upon our own earlier work
by expanding the space of recognizably monotonic programs, allow-
ing more programs to be veriﬁed as eventually consistent via CALM
analysis. In addition to providing richer semantic guarantees than
previous approaches, in our experience BloomL provides a natural
and straightforward language for building distributed systems.

8. DISCUSSION AND FUTURE WORK

A key aspect of BloomL is that it enables the composition of
consistent components. Rather than reasoning about the consistency
of an entire application, the programmer can instead ensure that
individual lattice methods satisfy local correctness properties (e.g.,

Acknowledgments
We would like to thank Martin Abadi, Emily Andrews, Peter Bailis,
Daniel Bruckner, Mosharaf Chowdhury, Tyson Condie, Sean Cribbs,
Alan Fekete, Ali Ghodsi, Jonathan Harper, Leo Meyerovich, Josh
Rosen, Evan R. Sparks, Matei Zaharia, and the anonymous re-

viewers for their helpful feedback on this paper. This work was
supported by the Air Force Oﬃce of Scientiﬁc Research (grant
FA95500810352), the Natural Sciences and Engineering Research
Council of Canada, the National Science Foundation (grants CNS-
0722077, IIS-0713661, IIS-0803690, and IIS-0917349), and gifts
from EMC, Microsoft Research, and NTT Multimedia Communica-
tions Laboratories.

10. REFERENCES
[1] P. Alvaro, T. J. Ameloot, J. M. Hellerstein, W. R. Marczak,
and J. den Bussche. A declarative semantics for Dedalus.
Technical Report UCB/EECS-2011-120, EECS Department,
UC Berkeley, Nov. 2011.

[2] P. Alvaro, N. Conway, J. M. Hellerstein, and W. R. Marczak.
Consistency analysis in Bloom: a CALM and collected
approach. In CIDR, 2011.

[3] P. Alvaro, A. Hutchinson, N. Conway, W. R. Marczak, and
J. M. Hellerstein. BloomUnit: Declarative testing for
distributed programs. In DBTest, 2012.

[4] P. Alvaro, W. R. Marczak, N. Conway, J. M. Hellerstein,

D. Maier, and R. Sears. Dedalus: Datalog in time and space.
In Datalog Reloaded. Springer Berlin / Heidelberg, 2011.
[5] T. J. Ameloot, F. Neven, and J. Van den Bussche. Relational
transducers for declarative networking. In PODS, 2011.
[6] K. R. Apt, H. A. Blair, and A. Walker. Towards a theory of
declarative knowledge. In J. Minker, editor, Foundations of
Deductive Databases and Logic Programming, pages 89–148.
Morgan Kaufmann, 1988.

[7] I. Balbin and K. Ramamohanarao. A generalization of the

diﬀerential approach to recursive query evaluation. Journal of
Logic Programming, 4(3):259–262, 1987.

[8] K. Birman, G. Chockler, and R. van Renesse. Toward a cloud
computing research agenda. SIGACT News, 40(2):68–80,
2009.

[9] Bloom programming language.

http://www.bloom-lang.org.

[10] S. Burckhardt, M. Fähndrich, D. Leijen, and M. Sagiv.
Eventually consistent transactions. In ESOP, 2012.
[11] S. Burckhardt, M. Fähndrich, D. Leijen, and B. P. Wood.
Cloud types for eventual consistency. In ECOOP, 2012.
[12] G. DeCandia, D. Hastorun, M. Jampani, G. Kakulapati,

A. Lakshman, A. Pilchin, S. Sivasubramanian, P. Vosshall,
and W. Vogels. Dynamo: Amazon’s highly available
key-value store. In SOSP, 2007.

[20] J. M. Hellerstein. The Declarative Imperative: Experiences
and conjectures in distributed logic. SIGMOD Record,
39(1):5–19, 2010.

[21] B. Ippolito. statebox, an eventually consistent data model for
Erlang (and Riak). http://labs.mochimedia.com/
archive/2011/05/08/statebox/, 2011.

[22] G. Köstler, W. Kießling, H. Thöne, and U. Güntzer. Fixpoint
iteration with subsumption in deductive databases. Journal of
Intelligent Information Systems, 4(2):123–148, 1995.

[23] L. Kuper and R. R. Newton. A lattice-theoretical approach to
deterministic parallelism with shared state. Technical Report
TR702, Indiana University, July 2012.

[24] L. Lamport. The part-time parliament. ACM TOCS,

16(2):133–169, May 1998.

[25] LinkedIn, Inc. Voldemort vector clock class. https:

//raw.github.com/voldemort/voldemort/master/
src/java/voldemort/versioning/VectorClock.java.
Accessed February 20, 2012.

[26] W. Lloyd, M. J. Freedman, M. Kaminsky, and D. G. Andersen.
Don’t settle for eventual: Scalable causal consistency for
wide-area storage with COPS. In SOSP, 2011.

[27] W. R. Marczak, P. Alvaro, N. Conway, J. M. Hellerstein, and

D. Maier. Conﬂuence analysis for distributed programs: A
model-theoretic approach. In Datalog 2.0, 2012.
[28] F. Mattern. Virtual time and global states of distributed

systems. In Workshop on Parallel and Distributed Algorithms,
1989.

[29] P. E. O’Neil. The Escrow transactional method. ACM TODS,

11(4):405–430, Dec. 1986.

[30] Oracle Corporation. Streams Conﬂict Resolution.

http://docs.oracle.com/cd/B10501_01/server.
920/a96571/conflict.htm.

[31] C. H. Papadimitriou. The serializability of concurrent database
updates. Journal of the ACM, 26(4):631–653, Oct. 1979.
[32] D. S. Parker, G. J. Popek, G. Rudisin, A. Stoughton, B. J.
Walker, E. Walton, J. M. Chow, D. Edwards, S. Kiser, and
C. Kline. Detection of mutual inconsistency in distributed
systems. IEEE Transactions on Software Engineering,
SE-9(3):240–247, 1983.

[33] P. Reiher, J. Heidemann, D. Ratner, G. Skinner, and G. Popek.

Resolving ﬁle conﬂicts in the Ficus ﬁle system. In USENIX
Summer Conference, 1994.

[34] K. A. Ross. Modular stratiﬁcation and magic sets for
DATALOG programs with negation. In PODS, 1990.

[13] C. A. Ellis and S. J. Gibbs. Concurrency control in groupware

[35] K. A. Ross and Y. Sagiv. Monotonic aggregation in deductive

systems. In SIGMOD, 1989.

[14] A. A. Farrag and M. T. Özsu. Using semantic knowledge of

transactions to increase concurrency. ACM TODS,
14(4):503–525, Dec. 1989.

[15] C. J. Fidge. Timestamps in message passing systems that

preserve the partial ordering. In Australian Computer Science
Conference, 1988.

[16] H. Garcia-Molina. Using semantic knowledge for transaction

processing in a distributed database. ACM TODS,
8(2):186–213, June 1983.

[17] M. Gelfond and V. Lifschitz. The stable model semantics for

logic programming. In ICLP, 1988.

[18] D. K. Giﬀord. Weighted voting for replicated data. In SOSP,

1979.

[19] P. Helland and D. Campbell. Building on quicksand. In CIDR,

2009.

databases. In PODS, 1992.

[36] M. Shapiro, N. Preguiça, C. Baquero, and M. Zawirski. A
comprehensive study of convergent and commutative
replicated data types. Technical Report RR-7506, INRIA,
2011.

[37] M. Shapiro, N. Preguiça, C. Baquero, and M. Zawirski.
Conﬂict-free replicated data types. In 13th International
Symposium on Stabilization, Safety, and Security of
Distributed Systems, 2011.

[38] SQLite Query Language: ON CONFLICT clause.

http://sqlite.org/lang_conflict.html.

[39] C. Sun and C. Ellis. Operational transformation in real-time

group editors: issues, algorithms, and achievements. In CSCW,
1998.

[40] C. Sun, X. Jia, Y. Zhang, Y. Yang, and D. Chen. Achieving

convergence, causality preservation, and intention

preservation in real-time cooperative editing systems. ACM
TOCHI, 5(1):63–108, Mar. 1998.

[41] D. B. Terry, M. M. Theimer, K. Petersen, A. J. Demers, M. J.
Spreitzer, and C. H. Hauser. Managing update conﬂicts in
Bayou, a weakly connected replicated storage system. In
SOSP, 1995.

[42] A. Van Gelder, K. A. Ross, and J. S. Schlipf. The

well-founded semantics for general logic programs. JACM,
38(3):619–649, 1991.

[43] W. Vogels. Eventually consistent. CACM, 52(1):40–44, 2009.
[44] W. E. Weihl. Commutativity-based concurrency control for
abstract data types. IEEE Transactions on Computers,
37(12):1488–1505, 1988.

[45] C. Zaniolo and H. Wang. Logic-based user-deﬁned aggregates
for the next generation of database systems. In The Logic
Programming Paradigm: Current Trends and Future
Directions, pages 401–424. Springer Verlag, 1999.

