This is the first post in a series about Seastar, the framework ScyllaDB is built on. We will go deep, with C++ code and drawings, but not so deep that a post turns into a source file.

ScyllaDB is a Cassandra-compatible database, and it says it gets up to 10 times the throughput of Cassandra. My first question was: where do these 10 times come from? C++ instead of Java? No garbage collector? These help. But the ScyllaDB team gives a different answer: Seastar.

Short answer: Seastar starts exactly one thread per CPU core, pins that thread to its core, and splits memory, connections and data between the cores. No two cores touch the same thing, so there is no mutex, no atomic and no context switch between threads. When one core needs something from another core, it sends a message on a lock-free queue. This model is called shared nothing, and this post is about it.

Where Seastar came from

Avi Kivity, the lead developer of KVM, made the first commit to Seastar on 10 August 2014. His company, Cloudius Systems, announced it in February 2015, and in September of the same year they released ScyllaDB on top of it. Later the company itself was renamed to ScyllaDB.

The official Seastar tutorial says that the inspiration and first use case for Seastar was ScyllaDB, a rewrite of Cassandra, and that with Seastar they reimplemented it with up to a tenfold throughput increase and lower, more consistent latencies. Note the “up to”, and that this number comes from the people who built it. But the fact that they name Seastar as the reason matters to us.

There is one more interesting point in the same tutorial. Cassandra was already asynchronous. But it read the disk through mmap’ed files. When a page of such a file is not in memory, touching it blocks the whole thread until the disk read is done. So it had to run several threads per CPU. Which means: threads again, context switches again, locks again.

Where does the performance go?

If a team wants to build a very fast database on top of a general-purpose framework, a big part of the CPU time goes to work that has nothing to do with the real job:

  • The CPU sits idle, instead of running instructions (even a simple for loop), until an I/O operation finishes or a lock is released.
  • Cores work on shared data. Every atomic, every memory fence, and every time a cache line moves from one core’s cache to another (this is called cache line bouncing), the core has to wait for the data.
  • The kernel moves threads between cores, and every context switch means a cold cache and a lot of extra work.

In a normal Spring Boot app you never see any of this. But if we want to build a high-performance system, this is the first place to fix. These delays look small, but at scale they add up to high latency and low throughput.

Let’s see it with an example. We have a multi-threaded server: a few threads listen on one port, accept new connections, read from them and answer. All connections are kept in one shared list:

C++
std::mutex mtx;
std::vector<int> connections;            // shared between all threads

void worker(int listen_fd) {
    for (;;) {
        int fd = accept(listen_fd, nullptr, nullptr);
        {
            std::lock_guard lock(mtx);   // everyone waits here
            connections.push_back(fd);
        }
        handle(fd);                      // blocking read and write
    }
}

// main: 16 threads, all running worker(listen_fd)

So far everything is nice, and it works. The problem: if two clients connect at the same moment, two threads want to change the list at the same time, so one of them waits behind the lock. Now imagine 16 threads and a few thousand connections per second. Boom, there goes our performance.

Figure 1: On the left, four threads share one list behind one mutex. Only one thread can add at a time, and the others (orange) wait. On the right, every core has its own list and nobody waits for anybody. This is a drawing, not a measurement: every thread gets a connection every 1.5 seconds, and adding it to a list takes half a second.

Yes, many frameworks do exactly this today, and it works well for them. But we don’t want a general-purpose framework. We want something that uses every core down to the last cycle. So what do we do?

The fix: shared nothing

The idea is simple: if threads share nothing, they need no locks.

  • Instead of a big thread pool, start one thread per core.
  • Pin every thread to its core, so the kernel can’t move it around as it likes.
  • Run a separate event loop on every thread.
  • Every thread listens on the port itself and keeps its own list of connections.
  • If two cores really need to talk, they send a message on a lock-free queue, not take a lock.

I built this by hand once before. In a feed handler that connected to Binance, my goal was zero context switches, so I changed the architecture like this: every feed has its own boost::asio io_context, its timers and connections only use that io_context, and every io_context runs on one thread that is pinned to one core.

Here is the same idea for a server. We call each core a shard:

C++
using reuse_port = boost::asio::detail::socket_option::boolean<SOL_SOCKET, SO_REUSEPORT>;

void pin_to_core(unsigned core) {
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(core, &set);
    pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
}

struct shard {
    boost::asio::io_context io;          // this core's event loop
    tcp::acceptor acceptor{io};
    std::vector<tcp::socket> conns;      // only this thread touches it, no lock

    void accept_next() {
        acceptor.async_accept([this](boost::system::error_code ec, tcp::socket s) {
            if (!ec) conns.push_back(std::move(s));
            accept_next();
        });
    }

    void run(unsigned core, unsigned short port) {
        pin_to_core(core);
        tcp::endpoint ep(tcp::v4(), port);
        acceptor.open(ep.protocol());
        acceptor.set_option(reuse_port(true));   // every shard binds the same port
        acceptor.bind(ep);
        acceptor.listen();
        accept_next();
        io.run();
    }
};

In main we create one shard and one thread per core and call run(core, 8080).

How can several sockets listen on one port? Normally the second bind on a port fails with Address already in use. This is what SO_REUSEPORT is for (since Linux 3.9). With it, several sockets can bind the same port, and for every new connection the kernel picks one of them from a hash of the source and destination address and port.

To be sure, I ran this code with 4 shards on Linux (in Docker) and opened 1000 connections to it, twice:

shard 0shard 1shard 2shard 3
Run 1258248238256
Run 2229253288230

The kernel split them almost evenly, and no shard knows anything about the other lists. The connection list needs no lock anymore, because only one thread touches it.

But how much does that matter? To find out, I measured only the list part. Every thread adds 2 million integers (stand-ins for file descriptors) to a list: once all into one shared list behind one mutex, once each into its own list. There is no accept and no I/O. It measures only the cost of sharing the list:

C++
// shared: one list and one mutex for every thread
for (int i = 0; i < OPS; ++i) {
    std::lock_guard lock(shared_mtx);
    shared_items.push_back(i);
}

// own: every thread has its own list, no lock
for (int i = 0; i < OPS; ++i)
    own[t].items.push_back(i);

Every case ran 5 times and I took the median. I ran the whole program twice, and the table shows the range of the two medians. The numbers are millions of adds per second, all threads together. I added a fourth case too, explained below:

ThreadsOne shared list with a mutexOwn list with its own mutexOwn list, no lockOwn list, no lock, but a shared cache line
1180–181174–184211–234207–228
217317–350427–462223–235
433–34258–378473–532322–336
829–33375–398560–612233–262

With one thread, the mutex costs 15 to 23%. But as soon as a second thread joined, the shared list got about 10 times slower. Two threads together did much less work than one thread alone! With 8 threads, the separate lists did 18 to 20 times more work than the shared one.

The second column shows that the lock itself is not expensive. There every thread has its own list, with a mutex that no other thread ever touches, and with 8 threads it was 12 to 13 times faster than the shared list. What is expensive is sharing, and it costs in two ways:

  • The cache line moves between cores. The last column has no lock and no shared data. Every thread has its own list, but the small list headers (three pointers: begin, end and capacity) sit next to each other in memory, so a few of them land in the same 64-byte cache line. Every push_back writes the end pointer, so that cache line keeps moving between cores. That alone cut the speed almost in half with 2 threads, and made it 2.3 to 2.4 times slower with 8. This is called false sharing.
  • Threads go to sleep. When the lock is taken, std::mutex doesn’t just keep waiting: the thread goes to sleep in the kernel (futex) and is woken up later. I counted context switches with perf on Linux: with 8 threads, the shared list had 135 to 141 thousand context switches for 16 million adds. All the separate-list cases had at most 14.

Two notes. First, this is only the list part. In a real server every connection also costs an accept, syscalls and network work, so the difference for the whole server is much smaller than these numbers. Second, I ran this in Docker’s VM on an M4 Pro with 8 vCPUs, and the numbers move a lot between runs. For example, the own list with 4 threads went from 427 to 794 in single runs. So look at the ratios, not at the exact numbers.

Figure 2: Every shard is one thread pinned to one core, with its own event loop, memory and connections. Every arrow is two one-way lock-free queues, and they are the only way shards talk to each other.

What Seastar does

Seastar takes this idea all the way:

  • One thread per core, pinned. The --thread-affinity option is on by default, and Seastar pins every thread to its core with pthread_setaffinity_np.
  • Memory is split too. Seastar has its own allocator and splits memory between the cores. The source calls it a share-nothing allocator: every core allocates from its own part. If a core frees memory that belongs to another core, Seastar doesn’t give it to its own allocator. It puts it on a list for the owner core, and the owner frees it.
  • No thread switches between tasks. Every core runs a scheduler that runs small tasks one after another, cooperatively. There is only one thread per core, so the kernel doesn’t need to switch between our pieces of work.
  • Messages only. If shard 2 needs data that lives on shard 5, it calls smp::submit_to(5, ...) with a function that runs on core 5, and gets the result back as a future. Behind it there is a boost::lockfree::spsc_queue for every pair of shards: one writer, one reader, no lock.

The same server in Seastar:

C++
seastar::future<> service_loop() {
    std::list<seastar::connected_socket> conns;    // this shard's connections only
    seastar::listen_options lo;
    lo.reuse_address = true;                       // SO_REUSEADDR, not SO_REUSEPORT
    auto listener = seastar::listen(seastar::make_ipv4_address({8080}), lo);
    for (;;) {
        auto res = co_await listener.accept();
        conns.push_back(std::move(res.connection));  // no mutex: no other thread sees conns
        // read and write on this connection, on this core ...
    }
}

int main(int argc, char** argv) {
    seastar::app_template app;
    return app.run(argc, argv, [] {
        // run service_loop on every shard
        return seastar::smp::invoke_on_all([] { return service_loop(); });
    });
}

No threads to start, nothing to pin, no io_context. app_template starts all the shards, and invoke_on_all runs the loop on each of them. The co_await and the future are exactly what the next post is about.

One thing I didn’t expect

I thought Seastar also used SO_REUSEPORT to spread connections. At first it did. But on 18 September 2015, four days before ScyllaDB was released, Glauber Costa made a commit called “temporarily disable SO_REUSEPORT”. The reason: the kernel spread connections without looking at how busy each core was, so some cores were overloaded while others sat idle.

That “temporarily” is still temporary. In today’s Seastar source this function always returns false:

C++
// FIXME: reuseport currently leads to heavy load imbalance.
// Until we fix that, just disable it unconditionally.
bool posix_reuseport_available() const { return false; }

This fits my own test. The kernel’s hash doesn’t look at load at all. It picks a socket from the addresses only. My connection counts came out almost even because the hash is uniform, not because the kernel cared which core was busy.

So who decides now? In the POSIX stack, only shard 0 opens the real socket and calls accept. Then it picks the shard with the fewest open connections and sends it the file descriptor in a message. The other shards have a virtual listener that only waits for these messages. When the connection closes, that shard sends a message back to shard 0 to decrease its counter.

So even this small counter is not an atomic. Only shard 0 touches it, and the others send it messages. This is their code, shortened:

C++
shard_id next_cpu() {   // on shard 0, for every accepted connection
    auto min_el = std::min_element(_cpu_load.begin(), _cpu_load.end());
    auto cpu = shard_id(std::distance(_cpu_load.begin(), min_el));
    _cpu_load[cpu]++;
    return cpu;
}

~handle() {   // the connection is closed, on its own shard
    (void)smp::submit_to(_host_cpu, [cpu = _target_cpu, lb = std::move(_lb)] {
        lb->closed_cpu(cpu);   // runs back on shard 0: _cpu_load[cpu]--
    });
}
Figure 3: On the left, with SO_REUSEPORT the kernel picks a socket from a hash of the addresses (the numbers are from the first run of my test). On the right, in Seastar's POSIX stack only shard 0 accepts connections, and it sends the file descriptor to the shard with the fewest open connections.

With Seastar’s own native stack on DPDK the story is different: the network card spreads packets between the cores’ queues with RSS. That is for another post.

What does it cost?

Shared nothing is not free:

  • A busy core is on its own. If one shard gets heavy work, the others can’t help it directly. We just saw how hard even spreading connections is.
  • Another core’s data means a message. Every time a request needs data from another shard, a message goes there and an answer comes back. So you have to split the data so that most requests finish on the core where they arrived.
  • Nothing may block. There is one thread per core. If you put a normal read or a lock somewhere, that whole core and all its connections stop. Remember Cassandra and mmap.

Wrapping up

Seastar takes everything that always killed performance, locks, context switches and shared memory, out of the main path of the program. Every core does its own work without disturbing the others, and when they must talk, they send messages. The result is a framework that can use every CPU down to the last cycle.

In the next post I’ll go inside one core: the reactor and its futures, the brain of the system.

Sources

— Abolfazl Abbasi

Join the conversation

Questions, corrections, and a different way of looking at it are welcome.