<?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 Alejandro Capdevila on Medium]]></title>
        <description><![CDATA[Stories by Alejandro Capdevila on Medium]]></description>
        <link>https://medium.com/@alcaptar?source=rss-f435ff82f6d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bm2zsw6O5y8Ml7Rw7QHKTA.jpeg</url>
            <title>Stories by Alejandro Capdevila on Medium</title>
            <link>https://medium.com/@alcaptar?source=rss-f435ff82f6d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:01:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alcaptar/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[No buscaba velocidad, buscaba tiempo]]></title>
            <link>https://medium.com/@alcaptar/no-buscaba-velocidad-buscaba-tiempo-b96329de37ac?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b96329de37ac</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[extreme-programming]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 19:23:34 GMT</pubDate>
            <atom:updated>2026-10-22T20:16:00.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Cómo construí una máquina de estados determinista que orquesta los agentes</p><h3>Intro</h3><p>Todos sabéis de sobra que el mundo de la ingeniería del software está un poco patas arriba, donde uno ya no sabe ni por donde le vienen las hostias. Cada semana hay una palabra de moda nueva, una nueva herramienta aparece para destronar a las anteriores.</p><p>Además, no paran de bombardearnos con la idea de que tenemos que ir a toda velocidad con la IA. Pero yo no estoy buscando velocidad. Yo lo que busco es tiempo. Tiempo para pensar en cómo va impactar esta nueva feature en mi sistema. Tiempo para analizar detenidamente la última incidencia que ocurrió. Tiempo para hacer mejor mi trabajo, no deprisa y corriendo.</p><p>Así que con esta visión, quise construirme una herramienta que me ayudase en mi día a día. Existen un sinfín de herramientas basadas en skills y markdowns, pero para mi no eran suficiente, no me sentía a las riendas de lo que estaba ocurriendo. Quería que mi proceso fuese determinista, que se ejecutase el flujo exactamente como yo quería. Para eso me acabé construyendo una máquina de estados en Python que era la que marcaba el flujo e iba llamando agentes por debajo. Vengo a presentaros cómo acabé construyendo mi “maquinillo”, y os dejo el enlace al repo en las conclusiones.</p><h3>Primeros pasos: subset de skills</h3><p>Quería empezar por algo sencillo, que me permitiese validar el concepto rápidamente sin demasiadas complicaciones. Así que primero de todo, antes de ponerme a montar nada, tenía que definirme cuál iba a ser el flujo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni9gjkNexDekKzawxyINrw.gif" /></figure><p>Más o menos así es como venía trabajando con la IA:</p><ul><li>Una primera etapa de recabar la idea que tenía en mi cabeza o entender el ticket que tenía asignado. La IA me resulta de gran ayuda para profundizar en el trabajo que hay que hacer, qué hay que tocar, qué impacto va a tener en el resto del código, etc.</li><li>Una vez esa parte ya estaba clara, le pedía que se pusiera a implementar. No a lo bruto, sino pasándole una serie de convenciones que contenían la forma en la que a mi me gusta trabajar. Criterios de diseño y arquitectura, testing, parallel changes, etc.</li></ul><p>Entonces, lo más simple fue pasarlo a skills, para así no tener que estar repitiendo una y otra vez los pasos que quería seguir. Además, no me compliqué la vida y me fui a reutilizar un framework con el que ya había estado jugueteando bastante: <a href="https://github.com/obra/superpowers">superpowers</a>.</p><p>De todo lo que aporta este framework, lo que más me gusta es la skill de “brainstorming”, una skill que se dedica a lanzarte preguntas para entender exactamente qué es lo que quieres hacer, y lo acaba volcando en un fichero de especificación. Entonces, me hice un pequeño wrapper de esa skill, que simplemente le venía a decir que cargase la skill de brainstorming, pero que luego no siguiese el flujo predefinido de superpowers, nada más.</p><p>Para la parte de la implementación hice cosas muy similares. Hice skills muy sencillitas, pero que me asegurasen que seguían convenciones de calidad de código que yo quería que se utilizasen: arquitectura hexagonal, tdd, etc.</p><h3>Hagamos que sea un poco más autónomo</h3><p>Como parte de la gracia de este experimento era que la IA fuese autónoma y no requiriese de estar yo delante para completar un desarrollo, de forma muy natural nació la necesidad de una pieza de validación. Esta pieza se encargaría tanto de validar que realmente la implementación cumple con las convenciones que yo había indicado, como que realmente se haya implementado lo que yo había pedido que se implementase. Vamos, que los criterios de acepcación que había definido en la fase inicial de brainstorming realmente estuviesen aplicados. De nuevo, simplemente me llevé ese conocimiento a una skill.</p><p>Pero luego no quería estar yo diciendo qué skill ejecutar y demás. De nuevo, mi objetivo era ir automátizando el proceso lo máximo posible. Así que también nació el coordinador, la pieza que conoce cómo es el flujo de desarrollo completo y cuales son cada una de las fases que tiene el mismo. Es la encargada de una vez finalizada el brainstorming, pasar a la implementación y luego a la validación. Además de volver a implementar aquellos hallazgos que encuentre el validador con un número de reintentos acotado.</p><h3>Primeras iteraciones del maquinillo</h3><p>Esto ya funcionaba francamente bien, pero la ejecución con skills acababa provocando que se me comiese la ventana de contexto de la sesión en la que estaba trabajando. Era conocedor de la degradación que sufren los LLMs según se va llenando la ventana de contexto, y hay varios estudios que indican que entre un 20–40% de contexto la sesión ya empieza a alucinar.</p><p>Entonces, la siguiente iteración fue realmente sencilla. Simplemente fue transformar las skills de implementación y validación en agentes, para que la sesión coordinadora fuese lanzándolos en segundo plano, y así el problema del contexto se veía reducido enormemente.</p><p>En este punto, empecé a ver que en algunos puntos de mi flujo necesitaba cierto determinismo. Entonces, empecé a crearme scripts que los agentes conocían para, por ejemplo, lanzar los tests, hacer commits con conventional commits, etc.</p><h3>Vayamos un paso más allá</h3><p>En este punto debo decir que el maquinillo funcionaba bastante bien. Me permitía ir saltando de un repo a otro haciendo modificaciones, pudiendo delegar esa implementación sin necesidad de que yo estuviese encima en todo momento. No obstante, cuando quería introducir cambios se sentía un poco como andar sobre arenas movedizas, no sabía realmente qué efectos iban a tener mis modificaciones. Si ahora le cambiaba el prompt al juez, ¿iba a obtener un mejor output? Si al implementador le indicaba que debía hacer hexagonal, ¿realmente iba a hacerlo?</p><p>Como supongo que ya habéis trabajado con agentes, ya sabréis que la respuesta es no, que nada te lo garantiza debido a su naturaleza indeterminista. Así que quise darle una vuelta extra y llevarlo un paso más allá. En lugar de ser el agente el que llamase un script, que fuese un script el que llamase a un agente.</p><p>Como he comentado antes, yo tenía muy claro cuál era mi ciclo de desarrollo. Al final no se trata nada más que un grafo, un árbol de toma de decisiones, donde dependiendo del resultado de la ejecución de cada uno de los nodos iba a tomar una decisión. Y esa decisión es algo determinista, no algo que quiera delegar en un agente.</p><h3>Maquinillo pasa a ser determinista</h3><p>Entonces, dándole vueltas y más vueltas, y buscando en por internet acabé teniendo la siguietne idea. ¿Y si en lugar de hacer que sea un agente el que llama a un script, sea el script el que llame al agente? ¿Por qué no darle la vuelta? Y ahí es cuando se me encendió la bombilla. Yo tenía muy claro cuál era mi flujo de trabajo, y quería que esos pasos ocurriesen sí o sí. Entonces construí una máquina de estados determinista que marcaba claramente el camino a seguir dentro del flujo. Cada uno de los estados representa el momento en el que se encontraba el desarrollo, y dependiendo del resultado de la ejecución, pues tomaba una decisión u otra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utFUQ3G06qvV8Oyud1u-Og.gif" /></figure><p>¿Que el implementador había terminado su trabajo? Pues lanzaba los tests y el linting del repo para validar que no había roto nada. ¿Que el validador decía que habían hallazgos de seguridad alta? Pues le devolvía esa información al implementador para corregir dichos defectos.</p><p>Las llamadas a los agentes las trataba como funciones sin estado, de usar y tirar, usando <a href="https://code.claude.com/docs/en/headless">claude -p</a>. Lo que hace este comando es ejecutar Claude Code sin sesión interactiva. De esta forma. que le pasas un prompt para que claude se ponga a trabajar, y cuando ha terminado devuelve un resultado y el proceso termina. Permite configurar qué herramientas puede usar y que te devuelva una respuesta estructurada.</p><p>Así el problema de la contaminación de contexto se iba de un plumazo, pues cada llamada se responsabilizada de hacer una única cosa, y al terminar la tiraba a la basura.</p><p>Además, me daba total control sobre que input le estoy dando al agente: un prompt concreto que no depende de cómo te hayas levantado ese día, los ficheros exactos que quiero que cargue, etc. La mejor forma de asegurar unos buenos tokens de salida es tener el total control sobre el input que le llega al agente.</p><p>Pude pasar a forzar una respuesta estructurada de los agentes, lo que a su vez me permitía tomar decisiones deterministas sobre las mismas. Al validar le puedo decir que me devuelva un informe con los hallazgos y con una severidad asociada, y yo puedo tomar la decisión de pedir correcciones solo para ciertas severidades, y con un número máximo acotado de reintentos. Que cuando lo hacía con agentes, tenían la tendencia de gastar todos los reintentos que tenían disponibles.</p><h3>Métricas, métricas y más métricas.</h3><p>Y lo más importante que vino con esto, las métricas. En el pasado <a href="https://medium.com/mercadona-tech/crafting-products-knowing-the-quality-of-what-youre-building-6ed5dd6b15a3">ya he insistido fuertemente en la importancia de las mismas</a>, ya que son lo que nos va a dar la visibilidad de si nuestra aplicación se está comportando como realmente esperamos. La ejecución con claude -p da toda una serie de metadatos sobre tiempos, costes, caché y tokens (entre otras cosas) que me permitía ver en qué se iba el dinero y el tiempo.</p><p>Con esto ya sé qué efecto tiene un cambio de prompting, de un fichero de convenciones, o de cualquier otro tipo de cambio con los que antes estaba tan inseguro. Me permite ver el impacto directo en dichas métricas, y así ver si realmente se comporta como realmente estaba esperando.</p><p>Mi visión era conseguir tiempo, tiempo para poder dedicarlo a otras. Me he sacado las métricas de 117 runs que hice durante 5 semanas, aquí lo tenéis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71RjusRbI3l7TV5XcYZ79g.png" /></figure><p>Y luego no menos importante, cuánta pasta cuesta esto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFOVARS1pp8N6yC_eW4wJA.png" /></figure><p>Como podéis ver, esto traga tokens. Si bien se puede ver una diferencia brutal con la apareción de los modelos 5.5 de Anthropic, tanto en dinero como en tiempo.</p><h3>Haz determinista aquello que debe ser determinista</h3><p>Los llms tienen una potencia tremenda, eso es algo más que evidente, pero su indeterminismo los puede convertir en herramientas poco fiables si queremos que un proceso siga siempre unos patrones determinados.</p><p>¿Quieres que siempre se lancen los tests? Ponte un hook o una máquina como la mía que siempre hace que se ejecuten. ¿Quieres que el validador solo mande a reimplementar hallazgos críticos? Pues ten un ifazo ahí puesto que te asegure esa regla ¿Quieres que el agente aplique hexagonal? Construye fitness functions que te aseguren que realmente se ha implementado la arquitectura como tú querías, tal y como ya hacíamos en la era pre IA. Además, el propio llm te puede ayudar en este trabajo.</p><p>Uno de los principales aprendizajes que me he llevado durante el tiempo que llevo usando llms es el propio título de esta sección. Si quieres que algo sea determinista, no lo delegues a un llm.</p><h3>Conclusiones</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEQQWME8HErTPFjLlk9WQg.gif" /></figure><p>No ha sido un camino de rosas. He tenido que dedicarle mucho tiempo, y mantenerlo al día tiene un coste nada despreciable. Soy consciente de que todavía está muy en pañales, que hay muchas cosas a iterar y corregir. Vamos, que no es un producto profesional. Pero con todos sus defectos, <a href="https://github.com/alcaptar/slice-runner">aquí os comparto el repositorio por si os sirve de inspiración</a>.</p><p>Gracias a él he podido aprender y sacar mis propias conclusiones. Y lo cierto, es que debo decir que funciona. Es capaz de implementar código y crear una pr sin supervisión, y que suele requerir de pocas cambios posteriores. Eso me ha liberado tiempo.</p><p>Tiempo para poder profundizar más en las implicaciones de la nueva feature. Tiempo para poder analizar una incidencia y entender realmente el causante de la misma. Tiempo para visualizar nuevos proyectos a desarrollar en el futuro próximo. Y esto me lo ha dado.</p><p>¿Es este el futuro de la programación? ¿Han venido esas factorías de software para ya automatizar nuestro rol? No tengo respuesta a esas preguntas, no me atrevería a responderlas con un experimento tan modesto. Si bien nuestro trabajo nunca ha sido coger tickets de jira y vomitar código dada esa hoja de requerimientos, o al menos no debería serlo.</p><p>Nuestro rol implica muchas más cosas, la implementación solo forma una parte de ella. Trabajar con los usuarios de nuestros productos, hacer cambios pequeños para poder recoger feedback cuanto antes y tener una visión de producto para entender qué merece la pena ser construido y qué no, analizar el impacto de nuestros cambios en producción, y un sinfín más de cosas. Los valores y principios de eXtreme Programming siguen más vigentes y son más necesarios que nunca. No desaprovechemos esta oportunidad en simplemente sacar más prs y líneas de código sin realmente entender qué estamos haciendo.</p><p>Lo que animo encarecidamente es que lo probéis. Ya sea con una herramienta vuestra, o con una del mercado. Hay herramientas como herder que vienen a ser algo muy similar a lo que describo. Probadlas, y sacad vuestras propias conclusiones. No dejéis que un random de internet (yo el primero) os convenza de cómo va a ser el futuro de vuestro rol. Descubridlo por vosotros mismos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b96329de37ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing in Python: How to effectively use Mock and create_autospec]]></title>
            <link>https://medium.com/@alcaptar/unit-testing-in-python-how-to-effectively-use-mock-and-create-autospec-a3158d125dd8?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3158d125dd8</guid>
            <category><![CDATA[craftsmanship]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Tue, 06 May 2025 19:33:15 GMT</pubDate>
            <atom:updated>2025-05-06T19:33:15.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing in Python, as in all languages, has some peculiarities that you need to be aware of in order to use it to its full potential. I myself made some mistakes when implementing some tests due to my lack of knowledge. Here is one of the lessons I learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*L_yUvIUVpkzuzUciGUNHYA.png" /></figure><h3>Setup</h3><p>All the cases I will show are based on a single use case: where a customer wants to pay for an order. I have simplified the example because the goal is to see the different testing strategies that can be used, not how to design this particular use case. To do this, I will use the following components.</p><p>An action for the payment of the order, which will orchestrate the different parts that are necessary to process the payment:</p><pre>class PayOrder:<br>    def __init__(self, order_repo: OrderRepository):<br>        self._order_repo = order_repo<br><br>    def execute(self, order_id: int) -&gt; None:<br>        order = self._order_repo.get(order_id)<br><br>        order.pay()<br><br>        self._order_repo.update(order)</pre><p>This requires a class representing the order itself:</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Order:<br>    id: int<br>    status: str<br><br>    def pay(self) -&gt; None:<br>        self.status = &#39;paid&#39;</pre><p>And a repository to interact with our persistence layer. Since I am only going to focus on unit testing the application layer, I only need a contract with this persistence layer, not the concrete implementation of it. This is the way Python allows you to create “interfaces” (in quotes, because we already know that in Python interfaces are a bit of a lie):</p><pre>from abc import ABC, abstractmethod<br><br>class OrderRepository(ABC):<br>    @abstractmethod<br>    def get(self, order_id: int) -&gt; Order:<br>        ...<br><br>    @abstractmethod<br>    def update(self, order: Order) -&gt; None:<br>        ...</pre><h3>Using patch.object or Mock</h3><p>One of the ways to test in Python is by using the <em>patch</em> decorator or by using the with <em>patch.object(…)</em> context. Using this tool, a possible test would be as follows:</p><pre>    def test_order_is_paid_with_patch(self):<br>        order_id = 1234<br><br>        with patch.object(DummyOrderRepository, &#39;get&#39;, return_value=Order(order_id, &#39;unpaid&#39;)) as mock_get:<br>            with patch.object(DummyOrderRepository, &#39;update&#39;) as mock_update:<br>                PayOrder(DummyOrderRepository()).execute(order_id)<br><br>        mock_get.assert_called()<br>        mock_update.assert_called()</pre><p>If you notice, this way of testing has forced me to make an implementation of <em>OrderRepository</em>, because I cannot make an instance of an abstract class to inject into the <em>PayOrder</em> action. Again, I insist that the purpose of this article is not about the concrete design of the action.</p><p>One possible implementation would be as follows:</p><pre>class DummyOrderRepository(OrderRepository):<br>    def get(self, order_id: int) -&gt; Order:<br>       return Order(id=1, status=&#39;unpaid&#39;)<br><br>    def update(self, order: Order) -&gt; None:<br>        ...</pre><p>But this should be a bit annoying by now. We have seen that this implementation is of no use to us, or if we were to use a real implementation (e.g. one that would store in a database using Django), we would be importing from the infrastructure layer in a test of our application layer.</p><p>Another similar but simpler approach would be to use the <em>Mock</em> object:</p><pre>    def test_order_is_paith_with_mock(self):<br>        order_id = 1234<br>        mock_repository = Mock(spec=OrderRepository)<br>        mock_repository.get.return_value = Order(order_id, &#39;unpaid&#39;)<br><br>        PayOrder(mock_repository).execute(order_id)<br><br>        mock_repository.get.assert_called()<br>        mock_repository.update.assert_called()</pre><p>Looks good, doesn’t it? We no longer have that weird import that was bothering us, and the test is green, covering our use case. But unfortunately, this implementation has a pretty serious problem. If we go to the <a href="https://docs.python.org/3/library/unittest.mock.html?utm_source=chatgpt.com#auto-speccing">official Python documentation</a>, it warns us of the following:</p><blockquote><em>Before 3.5, tests with a typo in the word assert would silently pass when they should raise an error. You can still achieve this behavior by passing </em><em>unsafe=True to Mock.</em></blockquote><p>What does this mean? Well, if we were in a previous version of Python 3.5, the following test would be green, even though we are not really validating anything, because a typo has been made:</p><pre>    def test_order_is_paid_with_mock_and_a_typo(self):<br>        order_id = 1234<br>        mock_repository = Mock(spec=OrderRepository)<br>        mock_repository.get.return_value = Order(order_id, &#39;unpaid&#39;)<br><br>        PayOrder(mock_repository).execute(order_id)<br><br>        # typo in the assert method, and this passes<br>        mock_repository.get.asert_called()<br>        mock_repository.update.assert_called()</pre><p>If we’re still using Python 3.5 at this point, it means we have more serious problems than this, so we shouldn’t worry too much. However, there is another problem that we are not covered for. Let’s go back to the <a href="https://docs.python.org/3/library/unittest.mock.html?utm_source=chatgpt.com#unittest.mock.create_autospec">official documentation</a> and look at the following:</p><blockquote><a href="https://docs.python.org/3/library/unittest.mock.html?utm_source=chatgpt.com#unittest.mock.Mock"><em>Mock</em></a><em> is a very powerful and flexible object, but it suffers from a flaw which is general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the </em>old api<em> but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.</em></blockquote><p>That is, if we now modify our action implementation to look like this:</p><pre>class PayOrder:<br>    def __init__(self, order_repo: OrderRepository):<br>        self._order_repo = order_repo<br><br>    def execute(self, order_id: int) -&gt; None:<br>        order = self._order_repo.get(order_id)<br><br>        order.pay()<br><br>        self._order_repo.update(order, &quot;this_is_a_wrong_argument&quot;)</pre><p>We see that the call to our repository’s <em>update</em> method now does not match the contract we defined, but the test remains green. A change like this might go unnoticed, but it would cause a spectacular crash in production.</p><h3>Using create_autospec</h3><p>Fortunately, there is a solution to this problem. At the test level, we can force the mock we defined in the test to conform to the specification we specified. To do this, let’s go <a href="https://docs.python.org/3/library/unittest.mock.html?utm_source=chatgpt.com#unittest.mock.create_autospec">back to the official documentation</a>:</p><blockquote><em>Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the </em>spec<em> object as their spec.</em></blockquote><blockquote><em>Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.</em></blockquote><blockquote><em>If </em>spec_set<em> is </em><em>True then attempting to set attributes that don’t exist on the spec object will raise an </em><a href="https://docs.python.org/3/library/exceptions.html#AttributeError"><em>AttributeError</em></a><em>.</em></blockquote><p>That is, if we now modify our test to look like this:</p><pre>    def test_order_is_paid_with_autospec(self):<br>        order_id = 1234<br>        mock_repository = create_autospec(OrderRepository, spec_set=True, instance=True)<br>        mock_repository.get.return_value = Order(order_id, &#39;unpaid&#39;)<br><br>        PayOrder(mock_repository).execute(order_id)<br><br>        mock_repository.get.assert_called()<br>        mock_repository.update.assert_called()</pre><p>We get the following error when we run it:</p><pre>TestPayOrder::test_order_is_paid_with_autospec - TypeError: too many positional arguments</pre><p>Great! That’s exactly what we wanted, for the test to warn us that we have made a mistake in the implementation of our code.</p><h3>What happens if I can’t inject the dependencies?</h3><p>If you notice, we were able to take advantage of create_autospec because we injected the repository into our action. I strongly recommend abstracting all those infrastructure components (databases, external requests, I/O processes, etc.) from our use cases. This will help us to abstract unnecessary details from our use case and, as you have seen, it will make testing easier.</p><p>But of course, what if we want to test only one of these layers? Let’s say we want to test this use case from the entry point (e.g. a Django view) and we also want to send an email to the user with the payment confirmation. In this case, we would want to set up an integration test to verify that all the pieces of our code are linked correctly, but we do NOT want to send an email every time we test.</p><p>In these cases, we will mock the call to this external library to prevent the email from being sent. The best thing to do is to wrap the call to the external library instead of mocking the library itself, and only check that we have called that wrapper. This way, we will be abstracting from the implementation details of that particular library, and we will prevent our tests from failing if any of those details change.</p><h3>Conclusions</h3><p>In short, to do unit testing in Python, the best tool is to use create_autospec and enable the spec_set=True option to be sure that we are testing what we expect.</p><p>This will save us a good scare in production, I can tell you from experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3158d125dd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Beast: Overhauling a Legacy Routing Engine Without Losing Our Way]]></title>
            <link>https://medium.com/mercadona-tech/taming-the-beast-overhauling-a-legacy-routing-engine-without-losing-our-way-788e2a8bae2b?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/788e2a8bae2b</guid>
            <category><![CDATA[lean]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[quality-software]]></category>
            <category><![CDATA[craftsmanship]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 08:31:01 GMT</pubDate>
            <atom:updated>2024-12-04T18:12:35.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-B1C2HV161ZGTYTqOe795Q.png" /></figure><p>I get to the office in the morning like any other day, join my teammates daily to check the progress of the tasks, and then we go for a coffee together. Everything would be like any other day, except that this time the team is faced with a big challenge: modifying the routing engine of our delivery application.</p><p>Let’s see why this is not just any task, and why it made us stop and think about how to approach it.</p><h3>Just some context</h3><p>To date, the routing engine has performed flawlessly. It supports nearly 150 stores with a fleet of approximately 460 trucks and ships more than 5,000 orders every day. As a result, any error could result in routes not being generated to deliver orders to our customers, which would have a significant impact on our business.</p><p>On top of that, it is a code that was written several years ago, and over time it has degraded to the point that just trying to read it is a challenge.</p><p>With those numbers on the table and the prospect of a big ball of mud, making changes to this engine is a little scary. A failure during the development of the new functionality could have a high economic impact, as well as a serious blow to the confidence that users have in our tool.</p><h3>The issue</h3><p>Here we encounter one of the most common problems in the industry: technical debt. <a href="https://www.youtube.com/watch?v=pqeJFYwnkjE">A term coined by Ward Cunningham</a>, it refers to the not-so-well-crafted code that we leave behind in order to get functionality quickly. Here you can read <a href="https://productcrafter.com/en/blog/tech-debt-is-like-gardening/#main">this post</a> by my colleague Emilio Carrión where he makes a more detailed analysis about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42in_NmVZiXp2wmSqajnHQ.png" /></figure><p>Therefore, it is foolish to attack the problem without a thought, knowing that we do not want to accumulate more debt. In Kent Beck’s recent publication, <a href="https://www.oreilly.com/library/view/tidy-first/9781098151232/">Tidy First?</a> the author presents three approaches to what he calls small cleanups. Although in this case, it is certainly not small, we will perform a similar analysis, considering three options:</p><ul><li>Clean the code before</li><li>Clean the code after</li><li>Do not clean it</li></ul><h3>Clean the code before</h3><p>My first instinct is to clean up first. Like many people, I like to see that the code is clean and understandable before I touch it. That way, it is much easier to introduce new changes with the confidence that we understand all the side effects that change may have.</p><p>However, let’s not forget that cleaning earlier comes with a big tradeoff: delaying when the feature will go into production.</p><p>One of the big premises of extreme programming is to deliver as much value as possible as quickly as possible. The sooner we make the new functionality available to our users, the sooner we get feedback on the changes we have made, whether or not what we have done makes sense, whether or not we have broken something that already exists, and so on. This cycle should be as short as possible so that we can learn more about the problem and refine the solution to the problem we are trying to solve.</p><h3>Clean the code after</h3><p>With this premise, the first thing we should do is implement the functionality as quickly as possible, without worrying too much about whether the code we are implementing is maintainable (not to be confused with being reckless and implementing things wildly). Once the code is in production and our hypotheses have been validated (or not), it is time to take care of the code and eliminate the technical debt we have created with our development. That way, our future selves will not want to kill us.</p><p>But of course, there is another side to the coin. It is very scary to touch legacy code. It is usually code that, if not properly maintained, has grown more and more complex over time until it becomes an indecipherable monster. At the same time, this code is already running part of your business, so failure to change it can have a huge economic impact. It’s an explosive combination that makes everyone nervous.</p><h3>Do not clean it</h3><p>A final option is not to clean up. There are cases where, after we have gone through a code flow, we know that it will never be touched again. No matter how maintainable and readable we want it to be, no one will ever set foot in that area again.</p><p>If that functionality is stable and does not cause any problems of any kind, then it makes no sense to spend time cleaning it up, since it will not bring us any benefit.</p><p>I should clarify that in my experience this has never happened. For one reason or another, the mess we leave behind always comes back with a vengeance, and the code we thought we would never touch again comes back to haunt us in our worst nightmares.</p><p>Therefore, I do NOT recommend this option. Doing even a little bit of cleaning will pay dividends in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXEgFl5FqCIEa8hdwKuAlQ.png" /></figure><h3>The challenge of changing the routing algorithm</h3><p>Okay, so after analyzing the different options, which one should we choose? Well, like everything else in life, it depends on the context.</p><p>In the case the team faced, we had to change the way truck routes were created. As mentioned earlier, the impact we could have in the event of an incident was enormous. In addition, this code had not been maintained for a long time and had not been properly cleaned up. Just understanding what this code was doing took a long time.</p><p>With this data on the table, we decided to spend some time cleaning it up first, until we were confident that we could safely introduce the changes.</p><p>So we had to roll up our sleeves and get in the mud, stop development as far as features were concerned, and start purging the weeds that had accumulated. At that point, we were very transparent with both our stakeholders and the rest of the team. As product engineers, we have a responsibility to know how to communicate and explain the importance of this cleanup, because at the end of the day, not delivering features has a direct economic impact on our business.</p><p>But not being able to pay the debt is also a problem. It will cost more and more to release new features, and when you want to change one, another one will break unexpectedly. Or even if a bug appears after a few months, it will take us several days to find the cause and several more to fix it.</p><p>Another aspect that is often overlooked is that this tangled code prevents us from seeing possible new features that we could easily add if we had paid the cost upfront.</p><h3>So how did we get to this point?</h3><p>In a normal development flow, where we are implementing functionality one step at a time, we need to understand what it means to consider a feature complete.</p><p>For example, let’s say we want to add a new button to our brand-new web page that, when clicked, will print a report. At first, we might think that if we can get the report to print, we are done. But we must remember that we still have some work to do. We will have some feature flags that need to be deleted, some strange names of some variables, some shortcuts that we should not keep in the code, etc.</p><p>This is a type of technical debt that we need to attack immediately after we deploy and validate the new functionality, because at that point we have more context for what we are doing, and it will be easier for us to pay that debt. In this way, if we are methodical, we will keep our code base in a healthy state that allows us to continue iterating it. This will prevent us from having to take a break to address it or, in the worst case, cause a project to derail.</p><p>One of the biggest mistakes people make when they’re trying to be LEAN is thinking that just doing the bare minimum to get a feature out is the same as writing shitty code. LEAN isn’t an excuse to make a mess of the code just to get it to production as soon as possible. Being LEAN means doing the minimum functionality needed given the current knowledge of the problem, not making spaghetti code without testing, with bad naming, all stuck in a single function, etc.</p><h3>Let’s wrap up</h3><p>In a nutshell, while missing a deadline can have economic consequences, failing to address technical debt can have a much bigger impact over time.</p><p>As professionals in the sector, we need to make sure we’re doing our jobs right and thinking about how today’s decisions will affect us tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788e2a8bae2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/taming-the-beast-overhauling-a-legacy-routing-engine-without-losing-our-way-788e2a8bae2b">Taming the Beast: Overhauling a Legacy Routing Engine Without Losing Our Way</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Products. Knowing the quality of what you’re building.]]></title>
            <link>https://medium.com/mercadona-tech/crafting-products-knowing-the-quality-of-what-youre-building-6ed5dd6b15a3?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed5dd6b15a3</guid>
            <category><![CDATA[craftsmanship]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[quality-software]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[lean]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Thu, 09 May 2024 11:55:57 GMT</pubDate>
            <atom:updated>2024-05-09T11:55:57.220Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of technology, it is crucial to ensure that the products we create maintain high quality. This article aims to provide an overview of how we can measure a product’s quality, from understanding what quality means to the various strategies we can use to evaluate and improve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoQjQMTqqhFgCwjCxRuPxQ.png" /></figure><h3>But… What’s that all about?</h3><p>First of all, what defines a quality product? Or what do we mean when we talk about the quality of a product?</p><p>Generally, we perceive a product as high-quality if it efficiently meets our expectations at all times. For instance, considering a jar of tomato sauce, we regard it as high-quality if it satisfies our taste, aligns with our health standards, and has a long shelf life.</p><p>The criteria for technological products aren’t that different. Ultimately, we want our application to function as expected, be user-friendly, avoid causing unexpected issues, and always be available. We can consider it a quality product if it meets all these requirements.</p><p>And, as always, everything depends on the context. When I joined my current team a couple of years ago, our product was giving service to 10 stores. The purpose of the application was very clear: solve new problems and add new features as we were discovering the needs of our users. But with time, we started expanding, and now we are providing service to over 1700 stores. Now, it is not just about adding features but also ensuring that operations run smoothly, the application is scalable and can endure sustainable growth in users as well as features.</p><p>So it’s really important to identify the purpose of what you’re building in your specific context. In Mercadona Tech, we say that if something is not helping to “sell lettuce,” then it is just a waste of time.</p><h3>And how do we measure it?</h3><h3>Metrics, metrics and more metrics</h3><p>Metrics will tell us user behavior and help us determine whether the application is really being used as expected or if it falls short.</p><p>Do users understand the new functionality? Are they using it? Does the new feature solve the need that was initially identified?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*hDluSg_7nQGRT0zxY4wZdQ.png" /></figure><p>Metrics should be able to answer all these questions (and many more), and their answers will indicate whether we are on the right track. This is where it is crucial to have a reliable system for tracking user feedback and a high level of maturity in terms of system observability to help you find out if something is not going as expected.</p><h3>Get down in the mud and ask users</h3><p>At Mercadona Tech, we are fortunate to be able to go to a store or warehouse and ask users directly. That gives us first-hand insights into how our products fit in and validate if they are really meeting our expectations.</p><p>But that’s not always the case, so you must enable a channel where users can give feedback. In this way, we will be able to gather all these inputs, identify our users’ concerns, determine if there are patterns that repeat themselves, etc.</p><p>Another indicator of a quality product is being able to do instant onboarding, where anyone familiar with the task knows how to use the tool. Just because it is an internal/logistic product, it doesn’t have to come with an instruction manual.</p><p>One of the KPIs used by our teams is the number of incidents/problems that our product records. This way, the whole team knows that the quality of our product is one of our top priorities.</p><h3>How much time does it take to add a new feature?</h3><p>We all want to work on new projects. It’s like working on a blank canvas, where decisions are not limited by previous work, and we can implement things a little bit as desired. Changes are introduced at an incredible speed, and everything goes smoothly.</p><p>Over time, without us noticing, what used to take a few hours now takes days and then turns into weeks. What used to be a simple change in functionality has now become an arduous job. Making adjustments to code on one side unexpectedly impacts other areas. Pipelines that used to run in minutes now take hours.</p><p>If we neglect good practices, we risk falling into a constant maintenance cycle without the ability to innovate or introduce new elements. Maintaining an application for 10 stores is not the same as maintaining an entire supply chain. This is a clear example of how, due to the product’s organic growth, our code has deteriorated to the point where it has become nearly unmanageable.</p><p>And even if you are careful with the product’s quality, some costs are inevitable and keep growing over time. This concept is known as <strong>basal cost</strong>. Here is a <a href="https://www.eferro.net/2015/09/coste-basal-del-software-vs-capacidad.html">post by Eduardo Ferro</a> (in Spanish) explaining it in detail. But don’t be mistaken. Taking good care of your product is essential to delay an unmanageable big ball of mud as much as possible.</p><p>Going back to my team example, when working for just 10 stores, we could add features quite easily. The codebase was small, the application’s load was reduced, and so on. But now, serving many more stores, we have to take into account other things when adding features: Is the database going to hold this? Are we going to be able to hold all that traffic? Do we have alerts that would warn us in case of an undesired behavior? How does this new feature interact with the existing one? And I could go on and on…</p><h3>The feared incidents</h3><p>Whenever we introduce something new, are we inadvertently breaking both existing and new functionalities in the process?</p><p>On one hand, incidents can have a technical root cause. If every attempt to introduce a new feature breaks something, it clearly indicates that our code lacks the necessary quality to keep pace with our development goals. There are also the old bugs that have been around longer than we have been in the company, but only palliative measures are taken and not corrective ones, often due to “lack of time.”</p><p>On the other hand, we may encounter user incidents related to our product, where users have difficulty understanding how to use it, leading to frequent errors.</p><p>And things get exciting when you start scaling. A feature can work wonders when used just by a few stores. We have a group called “laboratory,” these stores are used to undergoing constant changes, so they know how to handle unforeseen events. On a technical level, the complexity and amount of data we hold in this environment are limited.</p><p>But of course, it is quite another thing to launch that same functionality to the rest of the supply chain, where there are many more users with different profiles, the system has to withstand significant traffic and corner cases that are hard to predict. Some things “get through” lab, so we still need to keep iterating the solution once we get broader feedback.</p><h3>Ok then… What do we do now?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*kVQPd1H-D20316gIpdeYoQ.png" /></figure><p>First and foremost, it’s essential to identify the factors that have led to this situation. Typically, it’s not just one issue but rather an accumulation of various factors over time.</p><p>Knowing whether we comply with the quality standards required in our context is a constant exercise. It’s insufficient to conduct a checkpoint at a single moment and never revisit the topic.</p><p>Every time we have introduced a new feature into our systems, we should ask ourselves what difficulties we have encountered in doing so:</p><ul><li>Did it take longer than it should have because the code was not understood, or was it too tightly coupled?</li><li>Does our CI/CD system take too long to deploy our changes, so it takes too long to validate them?</li><li>Are many users getting in touch with us because they are confused?</li><li>Is our system scalable and can it endure sustainable growth in users and features, or is it constantly short on resources?</li><li>Are we frequently encountering corner cases that were not initially considered?</li><li>Most importantly, does the change have the desired outcome for the problem at hand?</li></ul><p>Identify if we are at a previous point and evaluate if it is necessary to stop and reevaluate our priorities before introducing new things.</p><h3>Let’s wrap up</h3><p>Ongoing journey that demands continuous evaluation and improvement:</p><ol><li><strong>Context Matters</strong>: The product’s purpose and context dictate its quality definition. As our product expanded from serving 10 to over 1700 stores, our focus shifted from adding features to ensuring scalability, operational smoothness, and sustained growth.</li><li><strong>Metrics and User Feedback</strong>: Metrics play a crucial role in understanding user behavior and validating whether the product meets expectations. Whether directly obtained or through channels, user feedback provides valuable insights into product usability and effectiveness.</li><li><strong>Balancing Speed and Quality</strong>: The speed at which we introduce new features should not compromise product quality. Monitoring the time required to implement changes, handling incidents, and maintaining scalability are essential aspects of balancing innovation and stability.</li><li><strong>Continuous Evaluation</strong>: Regular checkpoints and retrospectives are essential to assess whether quality standards are being upheld. Identifying underlying factors contributing to issues and reevaluating priorities are key steps toward maintaining product excellence.</li><li><strong>Learning from Challenges</strong>: Incidents and difficulties encountered during feature deployment offer valuable lessons for improving development practices. Understanding root causes and addressing fundamental issues ensures sustainable growth and innovation.</li><li><strong>Proactive Maintenance</strong>: Investing in proactive maintenance and addressing technical debt prevents the accumulation of challenges that can impede future development and innovation.</li></ol><p>By prioritizing these principles, we can effectively navigate the complexities of product development in a dynamic technological landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed5dd6b15a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/crafting-products-knowing-the-quality-of-what-youre-building-6ed5dd6b15a3">Crafting Products. Knowing the quality of what you’re building.</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous deployment. How to enhance the quality of our products.]]></title>
            <link>https://medium.com/mercadona-tech/continuous-deployment-how-to-enhance-the-quality-of-our-products-1a4db6e50179?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4db6e50179</guid>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 08:32:14 GMT</pubDate>
            <atom:updated>2023-11-17T08:32:14.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqAlNQhbUgu-oWUfJ0lwmw.jpeg" /></figure><h3>Introduction</h3><p>Hello there! I’m a backend developer on the Stocks team at Mercadona Tech.</p><p>Today, I want to discuss continuous deployment and its caveats. My goal with this article is to alleviate the natural apprehension associated with deploying in production. By providing reasons and data, I aim to demonstrate the potential impact on our products that can have this technique.</p><p>The mantra is the more frequent and faster, <strong>the better</strong>.</p><h3>So, what is it?</h3><p>OK, but first things first. What is continuous deployment? To keep it really simple:</p><p><em>It is a software development practice where code changes are automatically and continuously deployed to production environments without manual intervention.</em></p><p>While the concept is straightforward, it requires substantial work behind the scenes. So, why should we bother? What benefits does this approach offer? Here are a few reasons.</p><h3>OK, but why?</h3><h3>The deception of staging environments</h3><p>We’ve all been there. We’ve worked (or are working) in companies where we must pass our developments through specific pre-production environments to ensure they are high quality for deployment.</p><p>These environments exist to assure us that everything will go as planned and we won’t cause any issues in production. As part of this, we spend significant time setting up production infrastructure replicas, making daily copies of the production data to these environments to mirror them as closely as possible, and doing many other tasks.</p><p>However, experience has taught me that these environments don’t guarantee a smooth deployment. No matter how closely we try to mimic the production environment, they will never be an exact replica. And these differences tend to be a key factor.</p><p>It’s important to remember that users are unpredictable. Our app will likely be used in ways we haven’t anticipated and couldn’t possibly replicate in non-productive environment.</p><blockquote>💡 Rather than being helpful, non-productive environments can often become an obstacle in the development cycle.</blockquote><h3>To reduce incidents</h3><p>A common concern when deploying to production is the risk of causing incidents. Thus, the initial impulse is often to deploy as infrequently as possible, assuming this will minimize the potential impact on the production environment.</p><p>But let’s step back for a moment and take another look. The longer we postpone the release, the more features will gather in that release, increasing the probability of issues appearing in production.</p><p>If we opt for smaller deployments, with only one feature or even parts of a feature, the likelihood of causing an incident is significantly reduced due to its minimal impact on other parts of the product.</p><blockquote>💡 The later we make a release, the greater the risk of creating a high-impact incident.</blockquote><h3>To detect issues faster</h3><p>Keeping with the long releases issue, it will be difficult to identify and fix bugs in our application if we release updates every three months. Furthermore, recalling the reasoning behind specific programming decisions made months ago, which may have led to the problem, can be challenging</p><p>On the other hand, consider the scenario where we deploy once a day. If we detect a problem in our product, our main suspect would be the previous day’s release. Since this release contains a limited amount of code, it’s much easier to identify the problem.</p><p>With that, we will be able to reduce the <strong>impact</strong> of the incident dramatically.</p><blockquote>💡 The larger the release, the more difficult it is to pinpoint the source of an issue and the greater the impact on our business.</blockquote><h3>To add value</h3><p>To truly determine the value of a new feature in your product, the best approach is to put it into production. We can assess its true worth by observing how it impacts our product and how users interact with it.</p><p>In his book “Extreme Programming Explained,” Kent Beck emphasized the importance of minimizing feedback loops for an XP team to operate effectively.</p><blockquote>💡 The longer it takes to reach production, the longer the feedback loop becomes, and the greater the risk of wasting our time and money.</blockquote><h3>How to do it</h3><p>However, it is important not to make this decision hastily. Deploying without proper preparation can be negligent, resulting in serious problems that could quickly lead to failure.</p><p>Continuous deployment is just the tip of the iceberg. Behind it, several requirements must be met to implement it successfully:</p><ul><li>A <strong>continuous integration system</strong>, where our code is automatically validated and integrated into our repo.</li><li>A good level of <strong>observability</strong> in our product and systems allows us know the state of our application at any time (you can check <a href="https://medium.com/mercadona-tech/observability-in-stocks-8fd7fb5c6a46">the article I wrote</a> about it).</li><li>Tools such as <strong>Feature Flags</strong> (you can check <a href="https://medium.com/mercadona-tech/how-we-manage-feature-flags-f1641d0671c2">the article</a> by my colleague Felipe) to be able to react easily to a problem.</li><li>A <strong>culturally mature team</strong> (XP, TDD, pair programming, etc.)</li></ul><h3>Ok… But what about us</h3><p>Here is the <strong>lead time</strong> of my team during last October.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*MIXAa5Y9fBvgsegFWhWXww.png" /></figure><p>That time to deploy is just the time it takes to build and deploy the new image once the pull request has been merged.</p><p>The time in the branch is partially “polluted” by the dependabot, as it creates the branches really early in the morning. But we are already going to merge those pull requests once created automatically</p><p>And here is the <strong>deployment distribution</strong> in the same month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nZh1X_-xsns-i20qPfk8A.png" /></figure><p>It looks like on Thursdays, we don’t code that much 🤔 (spoiler: typically is the retro + planning day). Usually, we use Fridays for workshops and self-training.</p><p>At Mercadona Tech, we are fortunate to have a <strong>Developer Experience</strong> team. They have provided us with tools that allow us to deploy to a small portion of the production environment (referred to as a “lab”) immediately after merging a pull request. Furthermore, this release will automatically be deployed to the rest of the production environment 24 hours later.</p><h3>Wrap up</h3><p>Continuous deployment enables us to consistently modify and enhance our product in a rapidly evolving world. Therefore, establishing shorter feedback loops will allow us to:</p><ul><li>Decrease the number and impact of incidents.</li><li>Minimize incident recovery time.</li><li>Effectively enhance our product’s value.</li></ul><p>So, how do you manage your deployments? I would appreciate hearing about your experiences in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4db6e50179" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/continuous-deployment-how-to-enhance-the-quality-of-our-products-1a4db6e50179">Continuous deployment. How to enhance the quality of our products.</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Clean Tests. About documentation at Mercadona Tech]]></title>
            <link>https://medium.com/mercadona-tech/crafting-clean-tests-851dc0e4b1a?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/851dc0e4b1a</guid>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 08:08:36 GMT</pubDate>
            <atom:updated>2023-07-31T08:11:26.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoM0BIcXEY8XzDyNLF7Nlw.jpeg" /></figure><h3>Introduction</h3><p>In my organization we have found traditional documentation (referring to typical user manuals with hundreds of pages) not to be very useful, unless in specific cases. Our encounters with documentation have lead to confusion and incorrect assumptions about the application’s functionality.</p><p>Coders, let’s be honest, tend to be disorganized and documentation can easily become outdated due to laziness or forgetfulness. Furthermore, any time invested in writing documentation that nobody will read is wasted time that could have been used to add value to your application.</p><p>Much is said about the importance of tests, especially when developing features and verifying that they perform as intended in conjunction with techniques like TDD. However, an aspect often overlooked is using tests as documentation for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Ch2cMmH1go7N-_c9yF28KA.jpeg" /></figure><h3>Using tests to understand what your code does</h3><p>Tests have a very powerful utility in that they serve as the source of truth about what your code does. They are truthful and reliable: if they indicate that your code does something, it is indeed doing that. Additionally, the tests will be updated simultaneously with the production code.</p><p>This makes them excellent documentation tools. Whenever someone delves into an unknown piece of code, it should be easy to understand all the different use cases for which that code was created.</p><p>However, in many cases, we receive a reality check. This is not just about the necessity of having tests (if you don’t have them, you should begin creating them as soon as possible) but also about their readability.</p><p>We all know that productive code should be carefully crafted and strive for the highest quality possible. However, tests often get neglected, like the middle child who never receives attention from their parents. As the code evolves, tests can become complex and mutate without receiving proper review, resulting in unpalatable spaghetti code that no one wants to read. It can be a daunting task to make changes to these tests.</p><h3>Taking care of the tests</h3><p>That’s why we must avoid reaching that point. That’s why, when working with TDD and we are working in the refactoring phase, we must also refactor the tests.</p><p>Here I’m pointing out some simple techniques that can help in that tedious task. But there are many more that can be applied.</p><h3>Naming</h3><p>A simple change to a variable or method name can often be the difference between incomprehensible and clear code.</p><p>For example, given the following code:</p><pre>    def test_admin(self):<br>        user1 = User.objects.create(name=&quot;user1&quot;, type=&quot;regular_user&quot;, registry_date=datetime(2015, 1, 23))<br>        user2 = User.objects.create(name=&quot;user2&quot;, type=&quot;admin&quot;, registry_date=datetime(2021, 8, 11))<br>        user3 = User.objects.create(name=&quot;user1&quot;, type=&quot;regular_user&quot;, registry_date=datetime(2015, 1, 23))<br><br>        users = get_them()<br><br>        assert users == [user2]</pre><p>Can you say, in just one look, what is that test verifying? Or do you have to stop a second, and check the details of the creation of the users to know the difference between them?</p><p>Now let’s take a look at a different version of that same test:</p><pre>def test_retrieve_admin_users(self):<br>        regular_user = User.objects.create(name=&quot;user1&quot;, type=&quot;regular_user&quot;, registry_date=datetime(2015, 1, 23))<br>        admin_user = User.objects.create(name=&quot;user2&quot;, type=&quot;admin&quot;, registry_date=datetime(2021, 8, 11))<br>        another_regular_user = User.objects.create(name=&quot;user1&quot;, type=&quot;regular_user&quot;, registry_date=datetime(2015, 1, 23))<br><br>        adim_users = retrieve_admin_users()<br><br>        assert adim_users == [admin_user]</pre><p>Here, you don’t need to check the details of the users. It’s easy to see that the second one is the admin, which you except to retrieve after calling the action. The name of the test has also been changed to reflect what is being tested.</p><h3>Extract to method</h3><p>Another simple step is to extract repeated elements in our tests to a common function that adds semantic meaning to our actions.</p><p>So, if we have several tests where we do a similar setup:</p><pre>class MySuperAwesomeUserTests:<br><br>    def test_an_awesome_test(self):<br>        john = # a user with some specific configuration<br>        alice = # another user with a different configuration<br><br>        # testing and asserting something<br><br>    def test_another_awesome_test(self):<br>        john =  # a user with some specific configuration<br>        alice =  # another user with a different configuration<br><br>        # testing and asserting another thing<br>        <br>    # a lot more super awesome tests here with a similar setup</pre><p>It can be pretty helpful to move that setup to a standard function:</p><pre>class MySuperAwesomeUserTests:<br><br>    def _setup_initial_users(self):<br>        john = # a user with some specific configuration<br>        alice = # another user with a different configuration<br><br>    def test_an_awesome_test(self):<br>        self._setup_initial_users()<br><br>        # testing and asserting something<br><br>    def test_another_awesome_test(self):<br>        self._setup_initial_users()<br><br>        # testing and asserting another thing<br><br>    # a lot more super awesome tests here with a similar setupBuilder pattern</pre><h3>Builder pattern</h3><p>Often, we need to create a series of objects that serve as subjects for our tests. However, constructing these objects can be complex, and it may be hard to tell the differences between objects in one test and those in another. We can use the <a href="https://refactoring.guru/design-patterns/builder">builder pattern</a> to simplify matters to create these objects.</p><p>So, for example, if we have a user model like this one:</p><pre>@dataclasses<br>class User:<br>    name: str<br>    type: str<br>    registry_date: datetime</pre><p>We can create a builder class for this model:</p><pre>class UserBuilder:<br>    _name: str<br>    _type: str<br>    _registry_date: datetime<br><br>    def __init__(self):<br>        self._registry_date = datetime(2020, 1, 1)<br><br>    def with_name(self, name: str):<br>        self._name = name<br>        return self<br><br>    def with_type(self, status: str):<br>        self._type = status<br>        return self<br><br>    def with_registry_date(self, registry_date: datetime):<br>        self._registry_date = registry_date<br>        return self<br><br>    def build(self):<br>        return User(name=self._name, type=self._type, registry_date=self._registry_date)</pre><p>In that way, when having to create users for our tests, it could look something like this:</p><pre>some_user = UserBuilder().with_name(&#39;John&#39;).with_type(&#39;regular_user&#39;).with_registry_date(datetime(2023, 7, 14))</pre><p>So, as the model gets more complex, it’s really easy to keep creating our custom objects without much complexity. We can even set some default parameters in the builder constructor, as I did with the registry_date.</p><h3>Factory pattern</h3><p>In combination with the builder pattern, another very useful pattern for creating objects is the <a href="https://refactoring.guru/design-patterns/factory-method">factory pattern</a>. So, for example, the team can reach a consensus that John is a registered user and Alice is a system administrator.</p><p>So, if we reuse the builder from the previous example, we could create something like this:</p><pre>class UserFactory:<br>    def create_standard(self):<br>        return UserBuilder().with_name(&#39;John&#39;).with_type(&#39;standard&#39;).with_registry_date(datetime(2023, 7, 14))<br><br>    def create_admin(self):<br>        return UserBuilder().with_name(&#39;Alice&#39;).with_type(&#39;admin&#39;).with_registry_date(datetime(2021, 5, 19))</pre><p>And so, in our tests, we could have this:</p><pre>john: User = UserFactory().create_standard()<br>alice: User = UserFactory().create_admin()</pre><p>With this, even if the definition of the model changes and it expands over time, we can keep things really simple in our tests, as we will need to change the builder and the factory, and not every test where the users are being used.</p><h3>Conclusions</h3><p>Documentation might be a necessary evil in some contexts where, for example, engineers do not work in long-term squads, development is externalized and/or someone non-technical is expected to be able to read it.</p><p>However, I invite teams to reflect on the time spent on maintaining documentation, and instead use well crafted tests as a suitable and more effective alternative to document the code’s purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851dc0e4b1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/crafting-clean-tests-851dc0e4b1a">Crafting Clean Tests. About documentation at Mercadona Tech</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability in Stocks]]></title>
            <link>https://medium.com/mercadona-tech/observability-in-stocks-8fd7fb5c6a46?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd7fb5c6a46</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Wed, 03 May 2023 07:01:54 GMT</pubDate>
            <atom:updated>2023-05-03T12:45:07.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>Our application that allows stores to check the physical stock of products and perform actions related to provisioning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*FbN3A228H9obGbR29iYvtQ.jpeg" /></figure><h3>Introduction</h3><p>This article explores the concept of observability and its importance in application monitoring. Using the Grafana<strong> </strong>platform as an example, the article discusses how tracing and logging can be used to provide insight into application performance and identify issues that may be impacting performance or reliability. This publication also offers a step-by-step guide for setting up a custom Contextclass to manage trace_ids and using decorators to log function executions automatically. Finally, the article discusses the benefits of using tools like Prometheus and Grafana to collect and visualize application performance data in real time, enabling teams to proactively identify and address issues before they impact users.</p><h3>So… What is Stocks?</h3><p>Stocks is an application that allows stores to check the physical stock of products and perform related actions. Unfortunately, the database is not under our control; another department of Mercadona manages it. Consequently, we rely on API calls to access the information we require. This means that the flow of information is as follows:</p><p>V6 → MERCADONA → MERCADONA DB → V6.</p><h3>Orchestration</h3><h3>A bit of context</h3><p>Our goal here is to have information on the state of our application. To do so, the first step is to start tracing all our application’s actions. A trace is a series of connected spans representing a single logical operation. And a span represents a single unit of work within a trace, such as a server request or a database query.</p><p>By collecting and analyzing those traces, you can recreate the state of your application at a specific moment and understand how different components of your application interact with each other, identifying issues that may be impacting the performance or reliability of your application.</p><p>But be aware that tracing adds overhead to your application. Collecting traces requires additional processing and storage resources, which can impact the performance of your application.</p><p>Tracing requires planning and coordination. To get the most value out of tracing, you must carefully plan which spans to include in your traces and how to instrument your code to generate those spans. You must also coordinate with other teams or systems that may generate traces in your environment.</p><h3>To the code and far beyond</h3><p>Now that we know the theory let’s get down to work. To link all the different spans in a trace, you can use a unique identifier for each trace called trace_id. One way to do this is to use a middleware that processes all the requests that our API is receiving and sets a trace_id header on the request:</p><pre>from uuid import uuid4<br><br>class TraceIdMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        request.headers[&#39;trace_id&#39;] = str(uuid4())<br>        response = self.get_response(request)<br>        return response</pre><p>The next step is to check if the request already provides a trace_id header and use it if it exists:</p><pre>from uuid import uuid4<br><br>class TraceIdMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        trace_id = request.headers.get(&#39;trace_id&#39;)<br>        if not trace_id:<br>            trace_id = str(uuid4())<br>        request.headers[&#39;trace_id&#39;] = trace_id<br>        response = self.get_response(request)<br>        return response</pre><p>One problem here is that we are delegating all the responsibility of managing that trace_idto the middlewarewhen it shouldn’t. Also, we are setting the trace_idinto a request header. That means that if we want to make use of it, we must pass that request from one layer of our application to another.</p><p>As we are kind of lazy coders, adding that overhead to all of our functions seems a bit of an overkill (and also a really tedious work). Instead, we can create our own custom Contextclass that has all the logic to manage the trace_id, and makes use of the threading.localobject to store that id during the lifetime of a request.</p><pre>from uuid import uuid4<br>import threading<br><br>local = threading.local()<br><br>class Context:<br>  @staticmethod<br>  def set_trace_id(self, id):<br>    trace_id = id<br>        if not trace_id:<br>            trace_id = str(uuid4())<br><br>    local.trace_id = trace_id<br><br>  @staticmethod<br>    def get_trace_id(self):<br>        return local.trace_id<br><br>class TraceIdMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        Context.set_trace_id(request.headers[&#39;trace_id&#39;])<br>        response = self.get_response(request)<br>        return response</pre><p>And finally, if you’re using a Django app, you just have to do these final modifications:</p><pre>from django.utils.deprecation import MiddlewareMixin<br><br>class TraceIdMiddleware(MiddlewareMixin):<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def process_request(self, request):<br>        Context.set_trace_id(request.headers[&#39;trace_id&#39;])<br><br>    def __call__(self, request):<br>        response = self.get_response(request)<br>        return response</pre><p>And don’t forget to set up your middleware class in the Django settings file:</p><pre>MIDDLEWARE = [<br>    # ...<br>    &#39;myapp.middleware.TraceIdMiddleware&#39;,<br>    # ...<br>]</pre><p>This will enable the middleware for all requests in your Django project.</p><h3>Using the trace_id</h3><p>Okay, now we have a trace_id for all requests that go through our API, but we have to use it somehow. One possible solution is for our loggerto use that trace_idevery time we log anything. If you are making use of the logging library included in Python, this is how to set up a filter to make use of the trace_id:</p><pre>import logging<br>from context import Context<br><br><br>class TraceIDFilter(logging.Filter):<br><br>    def filter(self, record):<br>        record.trace_id = Context.get_trace_id()<br>        return True</pre><p>And then, add this filter to the logger config. A very basic config looks like this:</p><pre>from logging import config<br><br>config.dictConfig({<br>    # ...<br>    &#39;filters&#39;: {<br>        &#39;trace_id&#39;: {<br>            &#39;()&#39;: &#39;src.my_app.logging_filters.TraceIDFilter&#39;<br>        }<br>    },<br>  &#39;handlers&#39;: {<br>        &#39;console&#39;: {<br>            &#39;class&#39;: &#39;logging.StreamHandler&#39;,<br>      &#39;filters&#39;: [&#39;request_id&#39;],<br>        },<br>    },<br>    &#39;root&#39;: {<br>        &#39;handlers&#39;: [&#39;console&#39;],<br>        &#39;level&#39;: &#39;WARNING&#39;,<br>    },<br>  # ...<br>})</pre><p>And you’re good to go. All the logs from the same request will share the same trace_id.</p><h3>Let’s start logging something</h3><p>So now it’s time to use our trace_id everywhere. One of the first things that can be done is to start logging the start and the end of the execution of our functions. Something like this:</p><pre>def my_function(*args, **kwargs):<br>    logging.info(&#39;Starting my_function execution&#39;)<br>    # code goes here<br>    logging.info(&#39;Finished my_function execution&#39;)<br>    return result</pre><p>And automatically, those traces will include the <strong>trace_id</strong> we have set up before. But that would mean we should manually add those traces to all our functions, views, actions, etc. So here is where de <a href="https://refactoring.guru/design-patterns/decorator">decorator pattern</a> comes to the rescue:</p><pre>import logging<br>from functools import wraps<br><br>def logged_method(func):<br>    file_name = module.split(&#39;.&#39;)[-1]<br>    func_name = f&#39;{file_name}.{func.__qualname__}&#39;<br><br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        logger.info(f&#39;Starting {func_name} execution&#39;)<br>        result = func(*args, **kwargs)<br>        logger.info(f&#39;Finished {func_name} execution&#39;)<br><br>        return result<br><br>    return wrapper</pre><p>And that’s it. Now we just need to decorate our functions:</p><pre>@logged_method<br>def my_view(request):<br>    return HttpResponse(&#39;Hello, World!&#39;)</pre><p>And the output will look like this:</p><pre>Trace ID: 8b56f1d4-4c4a-4ba9-9d0f-5a5b5f5e5d5c<br>Message: Starting my_view execution<br>Start time: a_time<br>End time: another_time<br><br>Trace ID: 8b56f1d4-4c4a-4ba9-9d0f-5a5b5f5e5d5c<br>Message: Finished my_view execution<br>Start time: a_time<br>End time: another_time</pre><h3>Next steps</h3><h3>Prometheus</h3><p>There are always ways to improve, and even if Elastic APM is a potent tool when your primary concern is monitoring the performance of your applications, it has some limitations in more complex environments. It does not scale so well, especially when storing metrics from infrastructure and in large setups.</p><p>Here is where Prometheus shines. Prometheus is a tool for monitoring and alerting that collects data about your systems and services, stores it, and allows you to query it to understand how your systems are performing. Combined with tools like Grafana, you can identify and fix problems with your systems, ensure that they are running smoothly, and get notified if there are any issues.</p><p>But why stick with just one? We can get the best of both worlds. We just need to set up Elastic APM to monitor the application performance and use Prometheus to collect and store metrics from the servers and other infrastructure components. Then we can make use of tools like Grafana to visualize both types of data in the same dashboard.</p><p>To do so, we need to:</p><ol><li>Set up a Prometheus server or servers to collect and store metrics from your infrastructure.</li><li>Install and configure exporters on your servers to send metrics to Prometheus.</li><li>Configure your Prometheus server to scrape metrics from the exporters.</li></ol><p>And with that, you are ready to have complete control over the status of your systems. In case of failure, you will be able to replay all the steps that led your systems to fail and thus understand exactly what happened.</p><h3>Alerts</h3><p>The team has connected the API with Prometheus, making their alerting system about Prometheus´ own metrics. They have used a tool that wraps the Prometheus Python library to create these metrics, following a facade pattern to control external libraries in their domain and avoid any potential issues caused by updates.</p><h3>Grafana</h3><p>As a part of their observability efforts, the team has set up a panel in Grafana that allows them to monitor the performance of their applications in real time. The panel is connected to a TV, making it easy for the team to monitor how their applications are working at all times. This approach enables the team to proactively identify and address any issues, ensuring that their system runs smoothly and reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZlI9zaJQSxLbEXYxRUTiw.png" /><figcaption>Grafana panel of the namespace status</figcaption></figure><p>The absence of data in the visualizations we have set up in Grafana is a positive sign. This is because the visualizations are based on the data collected by our monitoring tools, which are set up to track every instance of system failure. Thus, the lack of data in the visualizations indicates that our system has been running smoothly without any significant issues. When there are problems, the monitoring tools will generate data, which will then be reflected in the visualizations.</p><p>This approach allows us to proactively identify and address issues in our system rather than simply reacting to problems after they occur. By tracking system failures and performance metrics in real time, our team is able to quickly identify and resolve any issues that arise, ensuring that our system runs smoothly and reliably.</p><p>Co-written by: Alejandro Capdevila &amp; Juanjo Ponz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd7fb5c6a46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/observability-in-stocks-8fd7fb5c6a46">Observability in Stocks</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing multi-tenancy in a production system]]></title>
            <link>https://medium.com/mercadona-tech/implementing-multi-tenancy-in-a-production-system-df2f9710d1d?source=rss-f435ff82f6d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2f9710d1d</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Alejandro Capdevila]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 08:04:59 GMT</pubDate>
            <atom:updated>2022-09-14T08:04:59.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5ClssQqGBckEpg3WDbt2w.jpeg" /></figure><h3>Introduction</h3><p>Hello there! My name is Alejandro, and I’m a backend developer at Mercadona Tech. Just as I landed in this company, I joined the Supply team, a very young development team (the oldest backend developer joined just one month before me) that had the challenge of migrating one of our applications into a multi-tenancy environment.</p><p>In this article, I will present how we faced this challenge, see what tools were used and how it was implemented, as well as the conclusions we reached after the whole process.</p><h3>Our goal</h3><p>One of the responsibilities of the team to which I belong is the development of an application called V6, designed to help in various daily management tasks of Mercadona stores.</p><p>Initially, each store had its own systems, which meant that every time we wanted to implement the application in a new store, it involved relatively extensive work to prepare the necessary environment.</p><p>Such a task can be accomplished without problems as long as the number of deployments is small. At the time of writing, Mercadona has more than 1650 stores. It is not hard to imagine that such a colossal task is practically impossible to accomplish, or at least not without having to involve an excessive number of people in the process. In other words, we could not scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*Lt12E6WmnS_Lp0g7" /></figure><p>But there is no need to panic. Fortunately, a lot has already been invented in this life, and there are techniques designed for this situation.</p><h3>Multi-tenancy</h3><p>In terms of software architecture, multi-tenancymeans that a single instance of an application serves different tenants, a tenant being a group of users or other systems with the same access privilege level.</p><p>Translating this to our environment means several stores would attack the same V6 deployment or tenant. In this way, several stores would share the resources of a single tenant, greatly facilitating the deployment task.</p><p>While I will focus on the code-level details of the challenge of migrating an application to multi-tenancy, I will not forget to mention the enormous work done by our colleagues at SRE to manage and prepare the systems to deploy the stores.</p><h3>Let’s get to work</h3><p>Making a structural change in an application already in production is not trivial.An error would lead to the degradation of the data in our database, affecting the day-to-day work of the stores.</p><p>This forced us to be extremely cautious when applying the necessary changes. For that reason, we decided to use the parallel changes methodology relying on the use of feature flags.</p><h3>First steps</h3><p>But what does all this mean at the code level? What did we really have to do? Put very briefly, we had to add a new field in practically all the tables of our database (specifically, the store identifier) and make the different actions of our application act accordingly depending on which store was executing them.</p><p>That is, given an initial inventory model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BN29eUjjFDYEAn0uPE3wg.png" /></figure><p>We had to move to a model that included the center:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fz_ZjJJD-4rq7A6kXt_ckA.png" /></figure><p>As already detailed by my colleague Juanjo <a href="https://medium.com/mercadona-tech/code-architecture-overview-of-supply-team-technical-challenges-eca9d5f1d996">in his article</a>, and taking advantage of the fact that we had to review the application from top to bottom, we applied the boy scout rule. In this way, we moved all the application logic in some views to actions. For more details on hexagonal architecture, I recommend <a href="https://pro.codely.com/library/arquitectura-hexagonal-31201/66748/about/">this Codely course</a>. That means that instead of having this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tm-NhMoZguKHxoESiVYbvg.png" /></figure><p>We move on to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ffbnkedkzYDj2ygFyAkcA.png" /></figure><p>This case is particularly simple and does not cost too much to make the change, but other actions were much more complex, and the update was not so trivial. And it is at this point that django-constraints come into action.</p><h3>Django-constraints</h3><p>It is a library designed to work with Django, allowing us to add some constraints to our models and act accordingly. Since the base library does not have all the required functionality, our coworkers took it upon themselves to enhance it to cover our use cases. Without their help, it would have taken us at least twice as long.</p><p>But how does it work? Quite simply. First, we have to update our model to include the constrains we want (in our case, the center):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMk38937fG-5Yd19NVA42Q.png" /></figure><p>Now our model inherits from ConstraintedModel and we indicate the constraints we want to apply to it. Thus, when implementing the action, it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCfIiND0GGdS1k99nBDp0g.png" /></figure><p>The code is the same as when we were not working with multi-tenancy; we just had to add the extra line of constraints.</p><p>With all this, we are ready to take all our actions and pass them to multi-tenancy, right? Hold your horses; no need to run. Remember that this application was already in production, with several stores using it daily. It would be irresponsible to start transforming all the actions on the fly, as we could easily cause an error and correcting it would not be trivial.</p><h3>Parallel changes</h3><p>Parallel changes is a <a href="https://martinfowler.com/bliki/ParallelChange.html#:~:text=Parallel%20change%2C%20also%20known%20as,expand%2C%20migrate%2C%20and%20contract">pattern designed to make changes to a contract that are backward compatible</a>. This pattern divides the whole process into three phases.</p><h3>Expand phase</h3><p>The first phase is the expansion phase. In it, you live with the legacy code while implementing the new code, deciding the execution of one or the other using a feature flag.</p><p>I cannot stress enough the importance of testing and following methodologies such as TDD. Tests were our safety net. They asked if we had broken any functionality or if everything was running smoothly. They allowed us to move forward slowly but surely, feature after feature, without fear of making mistakes. In this team, nothing goes up without tests. Period.</p><p>Therefore, we duplicated all the existing tests (and, by the way, we took the opportunity to revise and extend them) to verify the new code’s correct behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GEPeiE0_xVzwLSHcCLStg.png" /></figure><p>Once we have the tests in red covering all the different use cases, we move on to the implementation as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wyeql8JKgTuX3FU_7L3Lw.png" /></figure><p>As can be seen, the use of a feature flag provides us with a lot of robustness. In case of any error in the new code, we could quickly disable the flag so that the original code could be executed again. And all without the need for new deployments.</p><h3>Migrate phase</h3><p>During the expansion phase, customers (stores in our case) continued to use the legacy code, with the new implementations being totally transparent.</p><p>But once the new code is ready to be used, it is time to start migrating customers to multi-tenant.</p><p>First, a new tenant was created with V6 deployed, and a single lab store was migrated. While having a single store does not make it an actualmulti-tenant environment, it was helpful to see how all the actions and data behaved as expected.</p><p>Once we felt comfortable, the moment of truth came: to have a second store make use of that same tenant. Thanks to the efforts described above, the test was a complete success. V6 had been migrated to multi-tenant!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*LWYvUMZTd22FFPlR" /></figure><p>However, not everything went smoothly, as we encountered some problems during the migration. Due to some issues with the foreign keys of the tables, we could not migrate the data from the original databases to the tenant database. In our case, it was not a severe problem, as the application hardly saves any data. But all those who are about to embark on a similar adventure should keep this in mind.</p><h3>Contract phase</h3><p>Euphoric after our triumph, we were aware that our work was not finished. The whole expansion process translated into creating a vast amount of code. Practically, between testing and production code, we doubled the total number of lines of code. But that’s not a bad thing. At this point, this code had assured us that each of the steps we had been implementing worked correctly. Plus, all this “noise” was a constant reminder that we couldn’t just keep it.</p><p>Once the correct functioning of the application was verified in a multi-tenant environment, it was time to clean the house because of how we had prepared it; removing all duplicities that were no longer needed was really easy.</p><p>So the production code was as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZCbIJSQDrhMqRcK8cY8yw.png" /></figure><p>But this does not stop here. If we look at it, we see that we have had to pass the parameter center to the execute method, a parameter we should give to each child function in case there were any. This can be a real nuisance.</p><p>That is why we found a solution to avoid this problem: Using a context. Since all the calls that attack our views pass through a middleware, we can take advantage of it to store that value of the center:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4kSxVBOeA4CGoB38WUWkg.png" /></figure><p>Being the context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qDLOCFoTvY2vqOsb6Wutg.png" /></figure><p>There are several interesting points here. The first is the use of threading.local(). Basically, this variable allows us to store data at the thread level so that each request will have its values. The second is that since sending the center_idas an attribute in client requests is going to be mandatory, we throw an exception in case this has not been provided at the time we are going to make use of it.</p><p>With all this in place, our production code becomes the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1_ZIWOSRTyjX7EEsgIIag.png" /></figure><p>It already looks better since we no longer have to drag the center from one side of our code to the other. But we can even go a step further. Since now all our actions will include the line with constraints(...), we can take advantage of the decorator pattern. Thus, our decorator would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*le4CYn4aizN9qWg-JA_ddA.png" /></figure><p>This allows us to remove our dependency with django-constraintsfrom our actions and avoid duplicating the line with constraints(...)throughout our code. Finally, our action would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39D8Tz2BFlwZR20_gwqh4A.png" /></figure><p>And as far as tests are concerned, we simply had to remove the class with the legacy tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3R96kBHSeJkpZHubTinXTw.png" /></figure><h3>Conclusions</h3><p>The migration tomulti-tenant was a success despite our initial insecurity due to being such a young team (in terms of time within the team, some of us are starting to show gray hair).</p><p>The use of patterns like parallel changes , methodologies like TDD and feature flags and tools like django-constraints allowed us to attack the problem knowing that, in case of an incident, with a single click everything would work as it should.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2f9710d1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mercadona-tech/implementing-multi-tenancy-in-a-production-system-df2f9710d1d">Implementing multi-tenancy in a production system</a> was originally published in <a href="https://medium.com/mercadona-tech">Mercadona Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>