<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lorenzo Iacolare on Medium]]></title>
        <description><![CDATA[Stories by Lorenzo Iacolare on Medium]]></description>
        <link>https://medium.com/@lorenzo_iacolare?source=rss-dbecb0b6f648------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SI0UPax4WmoFdIQn0SNmWQ.jpeg</url>
            <title>Stories by Lorenzo Iacolare on Medium</title>
            <link>https://medium.com/@lorenzo_iacolare?source=rss-dbecb0b6f648------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:09:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lorenzo_iacolare/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Inspired by Airbnb’s Minerva: Building a Semantic Layer in Python]]></title>
            <link>https://medium.com/@lorenzo_iacolare/inspired-by-airbnbs-minerva-building-a-semantic-layer-in-python-d27714adb6f5?source=rss-dbecb0b6f648------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27714adb6f5</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Lorenzo Iacolare]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 07:42:02 GMT</pubDate>
            <atom:updated>2025-07-30T07:42:02.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWIzk_HTbqhP-y4z_6vmzg.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>In 2021 the Data Team at <strong>Airbnb</strong> published a series of <a href="https://medium.com/airbnb-engineering/how-airbnb-achieved-metric-consistency-at-scale-f23cc53dea70">articles</a> plus a <a href="https://youtu.be/s4xwqQb5v4k?si=x_jqUsXUaFnO1mwH">video</a> about <strong><em>Minerva</em></strong><em>, </em>an in-house metrics platform that offers, among other things, a centralised and participative source of truth for analytics, reporting and experimentation across their company.</p><p>This led me to a key question:</p><blockquote>Technically, how can this be done?</blockquote><p>To answer that, we first need to understand the problem a metrics store is designed to solve.</p><p>In any growing, data-informed company, a seemingly simple question can send shivers down the spine of the data team:</p><blockquote>What is our official number for monthly active users?”</blockquote><p>The problem is that the answer often depends on who you ask.</p><p>Marketing might calculate it one way, the product team another, leading to a battle of conflicting dashboards and eroding trust in the data itself. This is precisely the chaos that a centralised metrics platform like Airbnb’s Minerva was designed to tame.</p><p>By creating a single, governed source of truth for business logic, a metrics store ensures that when anyone asks a question about the data, they get one consistent, reliable answer.</p><h4><strong>Minerva Logic</strong></h4><p>The abstractions of metrics from the end user seems to be achieved through two <strong>layers of definitions</strong> (YAML config files) that, starting from origin data, are used to build a <strong>unified metric layer</strong> by providing instructions on how to query the underlying data.</p><p><strong>Denormalised Layer</strong></p><p>In the first layer there is some kind of <strong>virtual denormalisation</strong>:</p><p>Starting from origin data sources — like databases, warehouses and object storage buckets — a <strong>denormalised SQL definition</strong> for an event data model (sales, rentals, stays, etc.) is provided.</p><p>The goal here is to flatten the model to streamline analytical queries in later stages.</p><p><strong>Metrics and Dimensions Layer</strong></p><p>In the second layer metrics and dimensions definitions are built upon the denormalised event tables.</p><p><strong>Inquiries</strong></p><p>An <strong><em>Inquiry </em></strong>to the service can include multiple <strong>metrics and dimensions</strong> along with <strong>granularity</strong> specification and <strong>filters</strong>.</p><p>When an inquiry is made, Minerva seems to read from the various configs and dynamically generate SQL to appropriately fetch the data from origin and deliver it to the end user. To do so efficiently it uses a <strong>split-apply-combine </strong>strategy.</p><h4><strong>Minerva Architecture</strong></h4><p><strong>Core API</strong></p><p>This is the core service for processing inquiries: given a certain data request of metrics, dimensions and filters it <strong>reads the configurations</strong> defined in the aforementioned layers and <strong>compile SQL queries</strong> to <strong>fetch data </strong>correctly from the relative origins.</p><p><strong>SQL Client</strong></p><p>This is the interface that allows the Core API to talk to every tool and user through SQL. It consists of a <strong>MySQL wire protocol</strong> implementation that exposes a <strong>database interface</strong> to the end user and parses the requested SQL queries into Core API requests.</p><p>This enables natural communication with a range of different <strong>BI tools</strong> that already talk with MySQL databases.</p><p>It’s worth noting that this works as long as the BI tool implements <em>direct query connections</em> without storing data locally.</p><h3><strong>The implementation of Mimir</strong></h3><p>The next natural step for me was attempting to build something with similar base features: that’s how <a href="https://github.com/liaco/mimir">Mimir</a>, the very little sibling of Minerva, was born.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZiTuy64rRnZYU_vK58aKA.png" /><figcaption>A Mimir generic flow upon data request</figcaption></figure><h4><strong>Architecture</strong></h4><p>To build a small scale architecture for Mimir I used a few Docker containers and docker compose for orchestration:</p><ul><li>A core container that exposes the <strong>Mimir API </strong>(FastAPI) to process inquiries (this is where all the main abstractions of metrics and dimensions using configs happen)</li><li>A container that expose the <strong>SQL Client</strong> to query the Core API (based on <a href="https://github.com/barakalon/mysql-mimic">mysql-mimic</a>)</li><li>A PostgresSQL container for the test sample data</li></ul><p>To populate test data in the last container I used the <em>pagila </em>sample database available <a href="https://www.postgresql.org/ftp/projects/pgFoundry/dbsamples/pagila/">here.</a></p><h4>Logic</h4><p>The first part of the implementation consisted in designing configuration files and the associated classes in my code to read and combine them when they appear in a data request.</p><p>Some examples of configuration files used…</p><pre># sources.yaml<br><br># The source SQL can include the necessary joins and light transformations <br># to create a clean, denormalized view for analytics<br><br>rentals:<br>    team: sales-core<br>    name: rentals<br>    description: Rentals data for sales analytics<br>    dimensions:<br>      - dim_rental_category<br>    sql: |<br>        SELECT <br>        rental.rental_id,<br>        rental.rental_date as ts,<br>        rental.inventory_id,<br>        rental.customer_id,<br>        rental.return_date as return_ts,<br>        rental.staff_id,<br>        category.name as category_name,<br>        payment.amount as amount<br>        FROM rental<br>        JOIN inventory on rental.inventory_id = inventory.inventory_id<br>        JOIN film_category ON inventory.inventory_id = film_category.category_id<br>        JOIN category ON film_category.category_id = category.category_id<br>        LEFT JOIN payment payment on payment.rental_id = rental.rental_id<br><br>    time_col: rental.rental_date<br>    time_col_alias: ts<br>    connection_name: pagila_postgres</pre><pre># dimensions/dim_rental_category.yaml<br># The dimension SQL defines extra dimensions on top of existing ones on the source<br><br>name: dim_rental_category<br>team: sales<br>collection: sales-core<br><br>sql: |<br>    SELECT<br>    COALESCE(category.name, &#39;Uncategorized&#39;) as dim_rental_category<br><br>source_name: rentals<br>...</pre><pre># metrics/action_movies_rented.yaml<br><br>name: action_movies_rented<br>team: sales<br>collection: sales-core<br><br>sql: |<br>    SELECT<br>    SUM(CASE WHEN dim_rental_category = &#39;Action&#39; then 1 ELSE 0 END) as action_movies_rented<br>    FROM rentals<br><br>source_name: rentals<br>required_dimensions:<br>  - dim_rental_category<br>truncate_incomplete_granularity: true<br></pre><p>…and classes defined in the Core API code:</p><ul><li><strong>Inquiry: </strong>Main class to handle inquiries, it provides methods to split the data request into multiple atomic metrics requests, execute them in parallel and then combine all the data into one output.</li><li><strong>Atomic Query: </strong>Contains multiple dimension and metrics for a same source, has methods to combine the generated SQL from each object and query the data at origin.</li><li><strong>Metric and Dimension: </strong>In-memory object for Metrics and Dimension configs</li><li><strong>Source: </strong>In-memory object for the denormalised layer config</li></ul><p>With this classes and configs defined each Atomic Query should be able to combine source, dimensions and metrics instances to <strong>query the underlying data</strong> at the origin:</p><pre># Denormalised layer<br>WITH denormalised_layer as ( --- denormalized table definition built dynamically<br>  SELECT <br>  ...<br>  FROM pagila.rentals<br>  JOIN ...<br>  JOIN ...<br><br>)<br><br># Metric Layer<br>SELECT <br>...<br>COUNT(distinct ...) as ..., --- sample metric definition<br>FROM denormalised_layer<br>WHERE ...  --- global inquiry filter<br>GROUP BY ...</pre><p>Python class implementation:</p><pre>class AtomicQuery:<br>    &quot;&quot;&quot;Represents a single, executable query to a data source.<br><br>    This class is an internal component of an Inquiry. It builds the SQL for a<br>    given set of metrics and dimensions against a single source and executes it.<br><br>    Args:<br>        source: The Source object to query.<br>        mimir_engine: The MimirEngine instance.<br>        metrics: A list of Metric objects to include in the query.<br>        dimensions: A list of Dimension objects to group by.<br>        start_date: The start date for the query.<br>        end_date: The end date for the query.<br>        granularity: The time granularity for the query.<br>        global_filter: A SQL WHERE clause to apply to the query.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        source: Source,<br>        mimir_engine: MimirEngine,<br>        metrics: t.List[Metric],<br>        dimensions: t.Optional[list[Dimension]] = None,<br>        start_date: t.Optional[str] = None,<br>        end_date: t.Optional[str] = None,<br>        granularity: t.Optional[GRANULARITY] = None,<br>        global_filter: t.Optional[sqlglot.exp.Where] = None,<br>    ):<br>        self.name = f&quot;tbl_{os.urandom(15).hex()}&quot;<br>        self.mimir_engine = mimir_engine<br>        self.source = source<br>        self.dimensions = dimensions if dimensions else list()<br>        self.metrics = metrics<br>        self.required_dimensions = {<br>            self.mimir_engine.get_dimension(dim)<br>            for metric in self.metrics<br>            for dim in metric.required_dimensions or list()<br>            if dim not in [d.name for d in self.dimensions]<br>        }<br>        self.start_date = start_date<br>        self.end_date = end_date<br>        self.granularity = granularity<br>        self.global_filter = global_filter<br>        self.ast = self._build_sql()<br><br><br>    def _compile_metrics_request(self) -&gt; sqlglot.expressions.Select:<br>        ...<br><br>    def _build_sql(self):<br>        &quot;&quot;&quot;Builds the final SQL for the query.&quot;&quot;&quot;<br>        start_date_dt = (<br>            datetime.strptime(self.start_date, &quot;%Y-%m-%d&quot;) if self.start_date else None<br>        )<br>        end_date_dt = (<br>            datetime.strptime(self.end_date, &quot;%Y-%m-%d&quot;) if self.end_date else None<br>        )<br>        compiled_source = self.source.compile_source(<br>            dimensions=list(<br>                filter(None, [*self.dimensions, *self.required_dimensions])<br>            ),<br>            start_date=start_date_dt,<br>            end_date=end_date_dt,<br>        )<br><br>        return (<br>            self._compile_metrics_request()<br>            .from_(self.source.name)<br>            .with_(alias=self.source.name, as_=compiled_source)<br>            .where(self.global_filter)<br>        )<br><br>    def execute(self):<br>        &quot;&quot;&quot;Executes the query and returns the results as a pyarrow Table.&quot;&quot;&quot;<br>        if not self.source.connection:<br>            raise MimirQueryError(<br>                f&quot;Source &#39;{self.source.name}&#39; has no active connection.&quot;<br>            )<br><br>        return self.source.connection.query(sql=self.ast.sql())</pre><p>Instances of <em>AtomicQuery</em> accept a wide range of query parameters and provide methods to build the needed SQL and query a single metric from the origin.</p><p>To dynamically build and manipulate SQL queries in a robust way, I used the sqlglot library.</p><h4>Inquiries</h4><p>Since rarely a data request for analytics or reporting purpose consists only of one metric I built an <strong><em>Inquiry</em></strong><em> </em>interface that executes atomic metric queries against their sources and then combines them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*qM5tzt5egb3wcctihK3dlA.png" /><figcaption>An example of Inquiry executed through the Mimir Client against a Mimir server</figcaption></figure><p>The <strong>Inquiry</strong> interface uses a <strong>split-apply-combine</strong> paradigm to fetch multiple metrics in parallel, register them inside a <strong>DuckDB</strong> in-memory instance and combine them using full joins on shared dimensions.</p><pre><br>class Inquiry:<br>    &quot;&quot;&quot;Represents a request for data, orchestrating one or more AtomicQueries.<br><br>    This is the primary class that users interact with to query Mimir. It splits<br>    a request across multiple data sources, executes them in parallel, and joins<br>    the results.<br><br>    Args:<br>        mimir_engine: The MimirEngine instance.<br>        metrics: A list of metric names to include in the inquiry.<br>        dimensions: A list of dimension names to group by.<br>        start_date: The start date for the inquiry (YYYY-MM-DD).<br>        end_date: The end date for the inquiry (YYYY-MM-DD).<br>        global_filter: A SQL WHERE clause to apply to the inquiry.<br>        granularity: The time granularity for the inquiry.<br>        order_by: A SQL ORDER BY clause to apply to the inquiry.<br>        client_sql: A SQL query to use to combine the results of the atomic queries.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        mimir_engine: MimirEngine,<br>        metrics: list,<br>        dimensions: t.Optional[t.List[str]] = None,<br>        start_date: t.Optional[str] = None,<br>        end_date: t.Optional[str] = None,<br>        global_filter: t.Optional[str] = None,<br>        granularity: t.Optional[str] = None,<br>        order_by: t.Optional[str] = None,<br>        client_sql: t.Optional[str] = None,<br>    ):<br>        where_clause = sqlglot.select().where(global_filter).find(sqlglot.exp.Where)<br>        order_by_clause = sqlglot.select().order_by(order_by).find(sqlglot.exp.Order)<br>        self.mimir_engine = mimir_engine<br>        self.dimensions = [<br>            mimir_engine.get_dimension(dim) for dim in (dimensions or [])<br>        ]<br>        self.metrics = sorted(<br>            [mimir_engine.get_metric(metric) for metric in metrics],<br>            key=lambda metric: metric.source.name,<br>        )<br>        self.start_date = start_date<br>        self.end_date = end_date<br><br>        self.global_filter = where_clause.this if where_clause else None<br>        self.granularity = GRANULARITY[granularity] if granularity else None<br><br>        self.order_by = order_by_clause.expressions if order_by_clause else None<br>        self.__client_sql = sqlglot.parse_one(client_sql) if client_sql else None<br>        self.validate_inquiry()<br>        self.atomic_queries = self._split_queries()<br><br><br>    def validate_inquiry(self):<br>        &quot;&quot;&quot;Validates the inquiry to ensure that it is well-formed.&quot;&quot;&quot;<br>        ...<br><br>    def _split_queries(self) -&gt; t.List[AtomicQuery]:<br>        &quot;&quot;&quot;Splits the inquiry into a set of AtomicQueries, one for each source.&quot;&quot;&quot;<br>        return [<br>            AtomicQuery(<br>                source=source,<br>                mimir_engine=self.mimir_engine,<br>                dimensions=self.dimensions,<br>                metrics=list(metrics),<br>                start_date=self.start_date,<br>                end_date=self.end_date,<br>                granularity=self.granularity,<br>                global_filter=self.global_filter,<br>            )<br>            for source, metrics in itertools.groupby(<br>                self.metrics, key=lambda metric: metric.source<br>            )<br>        ]<br><br>    def _combine_queries(self) -&gt; sqlglot.exp.Select:<br>        &quot;&quot;&quot;Generate the query to combine atomic queries output.&quot;&quot;&quot;<br>        ...<br><br>    def dispatch(self) -&gt; pa.Table:<br>        &quot;&quot;&quot;Executes the inquiry and returns the results.<br><br>        Returns:<br>            A pyarrow Table containing the final results.<br>        &quot;&quot;&quot;<br>        logger.info(&quot;executing queries&quot;)<br>        with duckdb.connect(&quot;:memory:&quot;) as conn:<br>            with ThreadPoolExecutor() as executor:<br>                future_to_query = {<br>                    executor.submit(atomic_query.execute): atomic_query<br>                    for atomic_query in self.atomic_queries<br>                }<br>                for future in as_completed(future_to_query):<br>                    atomic_query = future_to_query[future]<br>                    try:<br>                        data = future.result()<br>                        conn.register(atomic_query.name, data)<br>                        logger.info(f&quot;Registered {atomic_query.name}&quot;)<br>                    except Exception as exc:<br>                        logger.error(f&quot;{atomic_query} generated an exception: {exc}&quot;)<br>                        raise Exception from exc<br><br>            sql = self._combine_queries().sql(dialect=&quot;duckdb&quot;)<br>            result = conn.execute(sql)<br>            return result.fetch_arrow_table()</pre><p>The pseudo SQL query executed inside DuckDB looks something like this…</p><pre>SELECT<br>dimensions,<br>…<br>metric_1,<br>metric_2,<br>...<br>FROM <br>(<br>  SELECT<br>  dimensions,<br>  …<br>  metric_1,<br>  metric_2,<br>  …<br>  FROM metric_1_tbl<br>  FULL JOIN metric_2_tbl USING(dimensions)<br>  FULL JOIN metric_3_tbl USING(dimensions)<br>  ...<br>)</pre><p>… where each metric table is the result of an atomic query executed against its origin that has been registered as a DuckDB table.</p><h4>SQL Client</h4><p>Lastly for enabling a wide pool of BI tools to connect to the Mimir API I deployed a <a href="https://github.com/barakalon/mysql-mimic">proxy server</a> that implements the <strong>MySQL wire protocol </strong>and passes queries to the core API.</p><p>The proxy server listens for standard MySQL queries. When it sees a query to the special <em>mimir.metrics</em> table, it intercepts it, parses the requested fields and filters using <strong>sqlglot</strong>, and translates them into a JSON request to the core Mimir API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*O0PDYAedKNC9DOKygZSSxA.png" /><figcaption>The SQL proxy in action</figcaption></figure><h4>What’s missing (a lot)</h4><p>This was of course a (fun) experiment on the basic working principles behind a metrics store / semantic layer and as such it still misses much in terms of scalability and completeness:</p><ul><li>It lacks robust error handling and has very <strong>basic validation tools</strong> (via <strong>CLI</strong>) for configurations</li><li>It relies on<strong> in-memory processing</strong> for combining the output of several metric queries, a more scalable approach could be using a powerful query engine with federated capabilities like Trino or StarRocks.</li><li>Although Mimir <em>ConfigLoader</em> is extensible by design my current example leverage a <strong>filesystem based implementation</strong> where each time they are requested config files are read straight from the filesystem, realistically it would be better to use a key-value store like Redis or Valkey.</li></ul><h4>Repository</h4><p>You can find the full Mimir project and source code <a href="https://github.com/liaco/mimir">here</a>.</p><h4>Acknowledgments</h4><p>A special thanks to the Airbnb team, for taking the time to write such a detailed series of article to showcase their great work.</p><p><a href="https://medium.com/u/c00b242128fe">Robert Chang</a>, <a href="https://medium.com/u/f1d3099f8ab7">Amit Pahwa</a>, <a href="https://medium.com/u/12e9eb440113">Shao Xie</a>, <a href="https://medium.com/u/407dc03ace1d">Toby Mao</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27714adb6f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>