Difference between revisions of "KDE PIM/Akonadi/Architecture"

Line 227: Line 227:
When a client wants to perform a search, they can either query the Xapian database directly in-process through a search query, which will return a list of Item IDs matching the query. The client can then retrieve the respective Items from Akonadi.
When a client wants to perform a search, they can either query the Xapian database directly in-process through a search query, which will return a list of Item IDs matching the query. The client can then retrieve the respective Items from Akonadi.
Second option is a so-called persistent search. Persistent search is represented as a Virtual Collection belonging to the virtual Search Resource. The virtual Collection holds a search query, which is re-executed whenever an Item changes and all Items matching the query are linked to the virtual Collection. This allows keeping a persistent filter for Items even across multiple different Collections.
A second option is a so-called persistent search. Persistent search is represented as a Virtual Collection belonging to the virtual Search Resource. The virtual Collection holds a search query, which is re-executed whenever an Item changes and all Items matching the query are linked to the virtual Collection. This allows keeping a persistent filter for Items even across multiple different Collections.
Search infrastructure is currently undergoing major overhaul codenamed "Make Indexing Great Again", see

Revision as of 23:13, 20 March 2018

Akonadi Concepts and Architecture

This document describes and explains the core elements within Akonadi (like Items, Collections, etc.) as well as the architecture of the entire solution (clients, agents, server, etc.) and how they interact with each other. The reason this is all explained in a single document is so that it's easier to see how all the dots connect.

Eventually, this should be moved or copied into Akonadi docs.

Basic Entities

The term Entity is often used as a common terms for all the elements described below.


Attributes are additional metadata that can be attached to other Entities (except for other Attributes). An Atribute has a type and a value. Client applications and Agents can define their own Attributes but there are also some pre-defined Attributes, like the "EntityDisplay" Attribute which allows customizing how an Entity is presented to user in clients (by setting custom display name, icon, background color etc.).


Item is an abstract representation of data. Items have metadata (ID, size, mimetype, etc.), payload parts (the actual data, e.g. email envelope, email head and email body) and attributes. An Item can represent an email, a contact, a calendar event etc. One Item has exactly one parent Collection.


Collection, as the name suggests, is a collection of Items. A Collection can also have child Collections, thus creating a Collection tree. Collections can also have attributes.

Virtual Collections

Virtual Collection is represented as a regular Collection, but it has a special property that it cannot own any Items nor it can have any subcollections unless they are virtual as well. Instead of being a parent of Items, Items are linked into Virtual Collections. One Item can be linked into multiple Virtual Collections.

Virtual Collections are typically used to hold search results, that is a Virtual Collection represents a search query and all ``Items`` linked to it are those that match the query.


Tag describes a common abstract relation between multiple Items. For example, a "Work" tag can be assigned to many emails, tasks and events (or rather Items representing those) that are somehow related to user's work. A single Item can have multiple Tags and a single Tag can be assigned to multiple Items.


Relation describes a specific relation between exactly two Items - for example we can have an "INVITATION" Relation between an Item that represents an email with meeting invitation and an Item that represents a calendar event that was created from the invitation email. Single Item can be in multiple Relations, even in multiple Relations of the same type, but there are always exactly two Items in each Relation.

Basic components


Server is the server process that other components talk to via the Akonadi Protocol. It manages the cached Entities and persists them in a database. Database is considered an implementation detail of the Server, no-one else knows about it or interacts with it.


Agents are single-purpose processes that get notified when an Entity is created, modified or removed from the Server. Example can be the MailFilterAgent which is notified whenever a new Item is created and if the Item holds an email, it will apply a local mail filters to it and store the change back in Akonadi.


Resources are special cases of Agents that synchronize data between Akonadi Server and a remote server - for example the IMAP resource synchronizes data between Akonadi Server and a chosen IMAP server. To have multiple IMAP accounts, a multiple instances of the IMAP resource are created. When talking about Resources and Agents we can talk either about Agent (or Resource) Type or Agent (or Resource) Instance. Type is the implementation of the Resource and Instance is a running instance of the Type. Types' are unique (e.g. there can only be a single Resource called IMAPResource, but there could be multiple Instances of the Type, i.e. multiple IMAPResource Resources running providing connection to different IMAP servers or accounts.


Clients are user-facing application like KMail or KOrganizer that presents data from Akonadi to users and allows them to interact with the data.

DB Tables

This is a brief description of tables in the database that the Server stores all the data in and how they relate to the Entities and components described above.


A standalone table that holds information about the current version of the schema. Nothing to get excited about.


Holds list of active Agent and Resources Instances.


Holds metadata about Items - ID, parent Collection, size etc. This is a very big table - one row per every email, contact, event etc.


PartTable holds the actual payload parts and attributes for Items. This is the largest table in Akonadi as it contains on average 3 rows per each row in PimItemTable.


Contains names of parts and attributes from PartTable (like PLD:ENVELOPE, PLD:HEAD, ATR:noselect, etc.) - this is a very small table (around 10 rows normally) and its purpose is purely to de-duplicate the often-repeated strings from the already-big PartTable.


MimeTypeTable holds list of mime types. This is a very small table and like PartTypeTable is used simply to de-duplicate repeated strings from the PimItemTable and to allow a many-to-many relation between Collections and mimetypes.


FlagTable holds Item flags, like "seen", "spam", "hasattachment" etc. The table only holds simple strings and is fairly small (we have around 20 flags).


A single Item can have 0-N flags and this table describes the relation. This is a fairly big table as it usually has more than one flag per each PimItem row.


The CollectionTable holds Collections - their ID, parent Collection, cache policy etc. This normally a small-ish table - one row per a mail folder, calendar, addressbook etc. Each Collection is owned by a Resource.


As a single Collection can have multiple mimetypes (those are actually mimetypes of Items that are permitted within this Collection) and this table describes the relation between CollectionTable and MimeTypeTable.


This table holds additional attributes for Collections. One Collection can have multiple Attributes, but an attribute belongs to exactly one Collection.


This table describes relation between Items and Virtual Collections. This does not describe parent-child relationship, that's in PimItemTable.collectionId. The size of this table varies depending on how much you use the "Search" feature in KMail.


TagTable holds Tags. Usually a small table, one row per Tag and people generally don't have more then a few dozen Tags (most people don't use this feature at all).


This table olds tag types - this is purely to de-duplicate common strings from TabTable.


A table equivalent to CollectionAttributeTable, but for Tags.


A single Tag can exist in various backends - for example an IMAP account can have a tag called "KDE" that user uses to tag all emails related to KDE with. A calendar account can also have a "KDE" tag that user can use to tag KDE-related events with. To user we want to represent these two tags as a single Tag, so that they can see everything tagged with "KDE" Tag regardless of whether it's an email or an event. However each backend identifies the Tag differently - the IMAP resource will identify the Tag as "$KDE" while the CalDAV resource will identify the Tag with some random UUID like "{abcde-ef012-3456}". This table holds a RemoteID for each Tag as seen by each Resource that has the Tag.


A single Item can have multiple Tags and this table describes the relation.


Holds Relations between two Items


An equivalent to TagTypeTable, but for Relations.

Some more concepts


Item ID, Collection ID, Tag ID is a database primary key but is exposed to clients to uniquely identify each Entity.

Remote ID

RemoteID is a string-based identifier that is used by the backend (IMAP server, CalDAV server etc.) to identify the Entity. On IMAP server this can be an IMAP UID for an Item, mailbox name for a Collection, for maildir this can be a filename of the email etc. This is only exposed to Resources, since those are the only ones to actually understand what the RID means.


GID is a string-based identifier extracted from the payload (Message-ID header in emails, UID in iCal events etc.) and is exposed to clients.

Payload Type

As described above the actual Item data (e.g. body of an email) as stored in PartTable as a BLOB in the data column. This is called the Internal Payload. To avoid storing massive BLOBs in the database, we store payloads larger than certain threshold (4kB by default) as files on the filesystem and the PartTable only refers to the filename on the filesystem. Those are called External Payloads. There are also Foreign Payloads but right now they are not actually used by anyone.


Akonadi is a cache, not a storage. New Items are downloaded from the backend services (IMAP server, CalDAV server, maildir, ...) by Resources and uploaded into Akonadi reguarily. Any changes done to Entities by clients (marking an email as read, creating a new event, deleting a contact etc.) are send to the respective Resource that owns the Item in question, and the Resource replays the change to the remote service. If the remote service is not available (let's say user is offline but they mark a bunch of email as read or move them to some other folder) the changes are recorded by the Resource and are replayed once network is available.

How the whole thing works together


All components communicate with each other via The Protocol. The protocol is a custom binary protocol with commands and responses. Each client opens a connection (called Session) to the Akonadi Server and can send commands to the server requesting or modifying data. The Session is also called Command Session or Command Bus.

Each client can open multiple Sessions with the server - this is useful because Sessions don't support command pipelining, meaning that next command in the queue is not sent to the server until a response to the previous command has arrived, which can cause undesirable waits for the user. For example in KMail, the message list and the message viewer have each their own Session. This way when the user opens a huge folder, they can click on the first email immediately and the message viewer can retrieve it through its own Session without having to wait for the message list to receive all emails from Akonadi first.

Note that the Protocol is an implementation detail and is not in any way exposed to the clients. Clients only interact with the Jobs API, which internally issues and handles the communication via the protocol.

Change Notifications

As described above, the protocol is a mechanism for the clients to communicate with the Akonadi Server. The second communication mechanism in Akonadi are the Change Notifications, which allow the Server to notify clients about changes.

Clients can express their wish to receive notifications by creating a new instance of Monitor (or ChangeRecorder, more on that below). The Monitor will establish a connection to the server (we call this subscription, as the client subscribes to receive notifications) and will upload to it which kind of notifications it's interested in. The scope can be changed at any time through the Monitor's API, the Monitor will always upload the new scope to the server.

Whenever another client modifies an Entity on the server (create/modify/move/remove/link/...) the server will generate a notification message that describes which Entities have changed, and how. It will then compare the notification message to the scopes of the subscribers to see if the subscriber is interested in this particular notification or not. If the notification message matches the subscriber's filter (we call it that the subscriber "accepts" the notification), the notification is sent over to the subscriber.

On the client side, the notification is received by the Monitor and put into a pipeline. The Monitor will inspect which Entities the notification concerns and will retrieve them all from Akonadi using the regular Job API. Once all Entities are received, the Monitor will emit the respective signal based on the type of the notification.

Under the hood, Change Notifications are using the Protocol as well, but each Monitor opens its own Notification connection (or Notification Bus) to the server in parallel to the Command Session.

Akonadi Control

akonadi_control is a small, but very important part of Akonadi. When you type "akonadictl start", or when you start an Akonadi-enabled application like Kontact, they will start the akonadi_control process. Akonadi Control is responsible for starting the Akonadi server and all configured Resources. It also automatically restarts them when any of them crashes. The second important role of Akonadi Control is that it provides a DBus interface to communicate with the Akonadi Resources.

Akonadi Server

In principle the Akonadi Server is very simple: it receives commands from clients, handles them by reading or writing to the database, sends back a response and if needed generates a Change Notification.

Each connection is handled in a separate thread on the server in a Connection object. This allows the implementation of the command handlers to be blocking and also allows to keep some context for each connection. Whenever a new command is received on a connection, it inspects which type of command it is and creates a respective Handler (e.g. StoreHandler, AppendHandler, MoveHandler, etc.)

For read ("Fetch") commands, the respective Handler will construct an SQL query to retrieve the requested Entities from the database. It will them serialize them into the Protocol and send them back to the client. In some cases, the Akonadi Server can first request that the Item payloads are first retrieved from the owning Resource - this is because Collections can have an expiration policy, meaning that after some timeout, Akonadi Server will delete the payload of the Items in that Collection from the database. When a client requests a payload of an Item that is missing the payload, the Akonadi Server will request the Resource that owns the Item (via a DBus call) to retrieve the payload and upload it to Akonadi using the standard Job mechanism. Once done, the Resource notifies the Server via DBus call again that it has finished and the Akonadi server continues with retrieval as usual.

For each write command, once the data are written to the database, the Server will generate a change notification describing what and how was changed.

The Server also provides search functionality in part, which is described in detail below.

Client API

From an application point of view, the Akonadi Server and The Protocol are just implementation details that they are not aware of and don't interact with directly in any way. The only means for clients to interact with Akonadi is through the client API.


Jobs are the core elements of the client API. A Job is a long-running asynchronous task that can retrieve data from Akonadi or modify them - e.g. ItemFetchJob retrieves Items from Akonadi, CollectionModifyJob modifies Collections etc. Once finished, the job emits the result() signal after which the client can handle the result of the Job.

Jobs are dispatched automatically from the event loop and they are queued on a Session. If the caller does not specify any Session, the default Session is used. Each Session can only handle one Job at a time.

Monitor and ChangeRecorder

The Monitor is used to listen for changes in Akonadi. It has signals for each type of change that can occur, so clients can connect only to those they are interested in. Monitors can also be customized to only listen to changes of a certain type or changes concerning a specific type of Entities or even only specific Entities.

ChangeRecorder is a subclass of Monitor. It does exactly the same job as Monitor but in addition to it, it saves each change notification it receives to a journal file. The user is responsible to call changeProcessed() whenever it handles a change upon which the ChangeRecorder will remove the notification from the journal and will dispatch next notification in the queue. ChangeRecorder is only very rarely needed by clients and is used almost exclusively by Agents and Resources, where it can record incoming changes in case the Resource cannot store them to the backend, for example, because it needs to be online to do that. In this case, all notifications will be stored in the ChangeRecorder's journal and once the internet connection is available again, the Resource will request the ChangeRecorder to replay all notifications from the journal so that it can upload the changes to the backend.

EntityTreeModel (ETM)

EntityTreeModel is a QAbstractItemModel which holds the entire tree of Collections and Items and keeps it up to date. It is possible to filter the content of ETM in many ways to only include Entities of a certain type or mime type. ETM is usually used in applications in combination with various proxy models. For example in KMail, the folder list and message list are both sharing the same ETM under the hood, but use various proxy models to display only a specific part of the tree in each view.

ETM automatically keeps itself up-to-date by using a Monitor. It is not possible to modify entities by changing them in the Model, instead the client should use a Job to modify the Entity and the model will be updated as it receives the notification from the Monitor.


As explained above, Akonadi Resources take care of synchronizing changes between Akonadi Server and the actual storage (IMAP server, CalDAV server, local iCal file, etc.) which I'll call backend for the purposes of this document.


Each Akonadi Resource has a ResourceScheduler, which holds a queue of tasks that the Resource should perform. In fact, the ResourceScheduler has several queues with various priorities. For example, a queue for tasks that write changes from Akonadi to the backend has the highest priority, while the queue to download new changes from the backend has a lower priority. Whenever the Resource receives a new task (more on tasks below) it puts it into the ResourceScheduler, which then dispatches it based on the priority by calling the respective method in the Resource implementation. Once the Resource is done with handling the task, it tells the ResourceScheduler that it's done and that it can schedule the next task.


In general, there are two types of tasks: ChangeReplay and Sync. ChangeReplay tasks have the highest priority and they represent a change in the Akonadi data that needs to be written to the backend. This can be a new flag being added to an email, or a new calendar event being created or a contact being removed. Sync tasks (FetchItems, SyncCollectionTree, SyncCollection etc.) are tasks that are asking the Resource to download any new changes from the backend and put them into Akonadi. Sync tasks do not write anything to the backend.

Change Replay

Change Replay tasks are created whenever the ChangeRecorder in the Resource is notified by Akonadi Server about a change. Change Notifications are described in detail below. ChangeRecorder will store the change notification into a file and will pass it to the ResourceScheduler. In case the Resource cannot handle the change, maybe because the Resource is offline and it needs network access to connect to the backend, the change remains stored in the ChangeRecorder's file until the Resource goes online again. When that happens the ChangeRecorder is asked to replay all the changes from the file by passing them to the ResourceScheduler.

Each Akonadi Resource implements an AgentBase::Observer interface. This interface has methods like itemAdded(item, parentCol), itemsRemoved(items), itemsFlagsChanged(items, addedFlags, removedFlags) etc. that must be implemented by the Resource. In those methods, the Resource implementation takes the changed data and writes it to the backend using the backend protocol/format (IMAP, CalDAV, ICal etc.). As the ResourceScheduler is replaying the tasks, depending on the type of the change it calls the respective method from the Observer interface, waits for the Resource to confirm that the change has been succesfully written to the backend and then schedules the next task and so on until it runs out of tasks in the queue or until another task arrives.


Resource Synchronization means retrieving data from the backend and storing them in Akonadi, so it's a uni-directional synchronization. Synchronization can be requested via Resource's DBus interface - either via SynchronizeCollectionTree task, SynchronizeCollection task (which synchronizes all Items within a specified Collection) or SynchronizeItem, which retrieves a specified Item. There's also SyncAll tasks, which schedules SynchronizeCollectionTree task followed by SynchronizeCollection task for each Collection. There are more tasks of course to sync attributes, tags etc. but they all work on the same principle.

The Resource does not have to synchronize the entire Item, for example for emails we often only synchronize the envelope, which is enough to display the email in the message list in KMail, and the actual body is retrieved on demand once the user opens the email in KMail and KMail requests the payload body from Akonadi.

item Synchronization happens by so-called merging process, when the Server tries to see if an Item with the same identification already exists in the Akonadi database and if so, it overwrites it with the newly received Item. Otherwise a new Item entry is created in the database. The merging happens using RID (RemoteID) or optionally GID in cases where RID is unstable. It's also possible to combine both.


Resources can be in an online or offline state. This is not related to network connectivity status, even a local-only resource like the Maildir resource can be in an offline state. The state indicates whether the Resource is able to store changes in its backend. For remote resources (like IMAP) the online/offline status often matches the online/offline status of the network connectivity, but it's also possible to manually switch a Resource to offline.

Resources which are in the Offline state store reject all Sync requests and store change notifications in the ChangeRecorder journal. Once the Resource switches back to online, it will first replay all pending changes from ChangeRecorder and then it will start processing Sync requests again.


Most Resources need a configuration - server to which to connect, credentials, sync frequency etc. The configuration dialog can be invoked through a DBus call to the Resource and runs within the Resource process.


There is a special agent called Akonadi Indexing Agent which listens to changes in Items and indexes the Items into a Xapian database. There's a separate database for emails, contacts, event, notes, and contacts parsed from emails (like senders, etc.).

When a client wants to perform a search, they can either query the Xapian database directly in-process through a search query, which will return a list of Item IDs matching the query. The client can then retrieve the respective Items from Akonadi.

A second option is a so-called persistent search. Persistent search is represented as a Virtual Collection belonging to the virtual Search Resource. The virtual Collection holds a search query, which is re-executed whenever an Item changes and all Items matching the query are linked to the virtual Collection. This allows keeping a persistent filter for Items even across multiple different Collections.

Search infrastructure is currently undergoing major overhaul codenamed "Make Indexing Great Again", see https://phabricator.kde.org/T7014

This page was last edited on 20 March 2018, at 23:13. Content is available under Creative Commons License SA 4.0 unless otherwise noted.