Skip to content

Ports & Adapters Architecture

A core principle of Protean is to keep the domain separate from the underlying infrastructure. Because of this separation, you can write and test your models before you choose any technology, and add the component for that technology when you are ready. This lets you delay your decision on technology until the last responsible moment, the latest point at which you can still decide without closing off options.

Protean's design is based on the Ports and Adapters architecture, also known as Hexagonal Architecture, allowing loosely coupled components that can be easily connected and swapped.

Ports are abstract interfaces that define a specific type of interaction between the application and the outside world. They define a protocol that can be implemented by concrete technology implementations called adapters.

Adapters connect the application to the outside world. Each adapter translates the exchanges between an external technology and a port. The port states what the application requires from that technology.

Protean exposes several ports with an array of built-in adapters for each port.

In-Memory Adapters

Every port ships with a complete in-memory implementation that is active by default. These are not stubs or mocks. They implement the full provider interface (CRUD, filtering, sorting, stream reads, consumer groups, data reset) using Python data structures instead of external services. This means you can develop and test your entire domain model without any infrastructure running.

Because memory adapters and real adapters share the same interface, you can run the same test suite in both modes: in-memory for fast development feedback, and real infrastructure for final validation. Switch with a single flag: pytest --protean-env memory. See Dual-Mode Testing for the full pattern.

Port In-Memory Adapter Default
Database memory Yes
Broker inline Yes
Event Store memory Yes
Cache memory Yes

Database Adapter Architecture

A database adapter has four components that work together to make database communication possible. Each adapter will override the corresponding base classes for each of these components with its own implementation.

Note

An exception to this rule is the Session class. It may be preferable to use the Session structures provided by the database technology as-is. For example, PostgreSQL adapter that is powered by SQLAlchemy uses (and returns) the sqlalchemy.orm.Session object provided by SQLAlchemy.

Provider

Port: protean.port.database.DatabasePort, with protean.port.database.RawQueryDatabasePort for raw queries

The Provider is the main component responsible for interfacing with the specific database technology. It contains the configuration and setup needed to connect to the database, and it provides methods for interacting with the database at a high level.

The Provider connects the application to the database: it opens and manages the connections the application needs. It also implements the behavior specific to its database, such as connection pooling, transaction management, and query optimization.

To add a new provider, subclass BaseDatabase first, then DatabasePort, and implement the Port's members for your database technology.

Data Access Object (DAO)

Port: protean.port.dao.DAOPort

The Data Access Object (DAO) is responsible for encapsulating the details of the database interactions. It provides an abstract interface to the database, hiding the complexity of the underlying database operations from the rest of the application.

The DAO defines methods for CRUD (Create, Read, Update, Delete) operations and other database queries, translating them into the appropriate SQL or database-specific commands.

By using DAOs, the application code remains clean and decoupled from the database logic. DAOs and lookups together provide a query API that works across various adapters.

To add a new DAO for your provider, subclass DAOPort and implement its methods for your database technology. Each method takes the session to run in as its first argument and leaves the session open. Protean wraps the adapter DAO in its own DAO service, which opens, commits and closes sessions outside a Unit of Work.

Session

The Session component manages the lifecycle of database transactions. It is responsible for opening and closing connections, beginning and committing transactions, and ensuring data consistency.

The Session provides a context for performing database operations, ensuring that all database interactions within a transaction are properly managed and that resources are released appropriately. The Unit of Work uses the Session to keep each transaction intact and to roll it back when an error occurs.

The Session object is usually constructed and provided by the database orm or technology package. For example, PostgreSQL adapter depends on the sqlalchemy.orm.Session object provided by SQLAlchemy.

Model

Base Class: protean.core.database_model.BaseDatabaseModel

The Model represents the domain entities that are persisted in the database. It defines the structure of the data, including fields, relationships, and constraints. It is also a high-level abstraction for working with database records, allowing you to interact with the data using Python objects rather than raw queries.

Models are typically defined using a schema or an ORM (Object-Relational Mapping) framework that maps the database tables to Python objects.

Implementing a model for your database technology can be slightly involved, as ORM packages can heavily depend upon internal structures. Every database package is structured differently. Consult existing models for PostgreSQL (SQLAlchemy) and Elasticsearch (Elasticsearch) for examples on constructing model classes.

Once you define a base model for your provider, Protean auto-generates the model class for aggregates or entities when needed. You can control this behavior by supplying an explicit hand-crafted model class for your entity.

Lookups

Lookups in Protean are mechanisms used to query the database based on certain criteria. Each lookup is a custom implementation of one type of filter. With lookups, you can run complex queries without writing raw SQL. Lookups are typically used in the DAO layer to fetch records that match specific conditions.

Refer to the section on querying aggregates for examples of lookups. Consult the documentation on your specific chosen adapter for more information. The adapter may support specialized lookups for efficient or technology-specific queries.

Capabilities

Database providers, brokers and event stores declare their capabilities, a set of flags indicating which features the adapter supports. This enables:

  • Capability-gated methods: Methods like raw() automatically check whether the provider supports them, raising NotSupportedError if not.
  • Automatic test selection: Protean's conformance test suite runs only the tests relevant to each provider's capabilities.
  • Informed technology decisions: Compare adapters at a glance using capability matrices.

Database capabilities are independent of each other, so a provider can declare any combination of them. Broker and event store capabilities, by contrast, are organized into hierarchical tiers. See Database Capabilities, Broker Capabilities, and What each event store guarantees for full details.

Provider Registry

Providers are discovered dynamically through Python entry points. Built-in adapters register under the protean.databases (databases), protean.brokers (brokers), protean.event_stores (event stores) and protean.caches (caches) entry-point groups. Third-party adapter packages register in the same way, making them automatically available after pip install.

This replaces the earlier hardcoded provider dictionary and lets adapters ship as separate plugin packages. External packages can add new database, broker, event store or cache adapters without modifying Protean source code. See Building Custom Database Adapters and Building Custom Brokers for guides.

Initialization

Adapters are initialized as part of Domain initialization. Protean creates the provider objects in the adapter and establishes connections with the underlying infrastructure.

If a connection cannot be established for whatever reason, the Protean initialization procedure immediately halts and exits with an error message:

# fragment
from protean import Domain

domain = Domain()

# Non-existent database
domain.config["databases"]["default"] = {
    "provider": "postgresql",
    "database_uri": "postgresql://postgres:postgres@localhost:5444/foobar",  # (1)
}

domain.init(traverse=False)

# Output
#
# protean.exceptions.ConfigurationError:
# Could not connect to database at postgresql://postgres:postgres@localhost:5444/foobar
  1. foobar database does not exist on port 5444

See also