<?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 Nico Garitagoitia on Medium]]></title>
        <description><![CDATA[Stories by Nico Garitagoitia on Medium]]></description>
        <link>https://medium.com/@nijotigajo?source=rss-1d851c92f973------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KRW-rllNYB-0SS30</url>
            <title>Stories by Nico Garitagoitia on Medium</title>
            <link>https://medium.com/@nijotigajo?source=rss-1d851c92f973------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:21:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nijotigajo/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[Los Sistemas Distribuidos Siguen Siendo Difíciles, Incluso con IA]]></title>
            <link>https://medium.com/@nijotigajo/lo-que-aprend%C3%AD-construyendo-un-importador-csv-distribuido-con-ia-224366c957ad?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/224366c957ad</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 14:58:54 GMT</pubDate>
            <atom:updated>2026-04-14T15:07:50.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*759nmwLl8BfxtUdA" /><figcaption>Photo by <a href="https://unsplash.com/@jaredmurray?utm_source=medium&amp;utm_medium=referral">Jared Murray</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>El 20 de marzo de 2026 empecé este proyecto como un ejercicio de arquitectura. La idea parecía acotada: importar clientes desde CSV, procesar el archivo en segundo plano y registrar el resultado de cada fila.</p><p>Tres semanas después, el 10 de abril de 2026, el repositorio ya tenía cuatro servicios, RabbitMQ, PostgreSQL, Flyway, Structurizr, logs estructurados, un stack local con Grafana, Alloy y Loki, recuperación con DLQ y un primer dashboard de operador.</p><p>Ese crecimiento tan rápido me dejó una sensación clara. Con IA se puede producir mucho código en muy poco tiempo. Lo delicado viene después: definir bien el sistema, sostener la arquitectura y seguir entendiendo lo que se ha construido.</p><p>Este post-mortem recoge esas lecciones. Para un TL;DR, las conclusiones están al final.</p><p><a href="https://github.com/Chudroy/csv-importer">Enlace al repo en Github</a>.</p><h3>Microservicios como campo de entrenamiento</h3><p>La aplicación importa registros de clientes desde CSV. Un usuario sube un archivo, el sistema crea un job, procesa el contenido de forma asíncrona, normaliza filas, crea o actualiza clientes y expone un resumen con filas creadas, actualizadas, fallidas o ignoradas.</p><p>Si hubiese tenido que mantener esto como producto, mi punto de partida habría sido un monolito modular. El propio <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/design-doc.md">design document</a> deja esta idea por escrito: la arquitectura distribuida se eligió para aprender, no por ser el camino más corto.</p><p>Quería practicar límites de servicio, workflows asíncronos, contratos de mensajes, idempotencia, fallos parciales, observabilidad y recuperación operativa. El resultado actual se reparte entre cuatro servicios:</p><ul><li>api-service, como borde HTTP público.</li><li>import-service, como dueño del estado de importación, lecturas y recuperación.</li><li>parser-service, escrito en Rust, como responsable de parsear y normalizar CSVs.</li><li>customer-service, como dueño de los datos de clientes y la reconciliación por email en v1.</li></ul><p>RabbitMQ transporta los mensajes. PostgreSQL guarda el estado durable. Flyway aplica migraciones, Structurizr documenta la arquitectura y Docker Compose levanta el entorno local.</p><p>Como ejercicio, funcionó muy bien. Como arquitectura base para un sistema pequeño habría sido una elección cara.</p><p>La lección encaja con <a href="https://martinfowler.com/bliki/MonolithFirst.html">MonolithFirst</a>, de Martin Fowler: conviene retrasar la distribución hasta tener una razón fuerte para pagarla. Un mal límite entre servicios implica contratos, persistencia, mensajes, tests, observabilidad y recuperación. Refactorizar deja de ser un cambio local.</p><h3>Documentar para pensar</h3><p>Lo más valioso al principio fue escribir arquitectura.</p><p>El primer artefacto importante fue el <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/design-doc.md">design document</a>. Ahí fijé propósito, alcance, requisitos funcionales, no-funcionales, atributos de calidad y decisiones v1: procesamiento asíncrono, RabbitMQ, PostgreSQL, almacenamiento de filas parseadas, matching por email y visibilidad de resultados por fila.</p><p>Después llegó el <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/roadmap.md">roadmap</a>. Con el tiempo se convirtió en la columna vertebral del proyecto. Cada fase tenía objetivo, features y definition of done. Cuando volvía al repo tras varios días, ese documento me devolvía el hilo sin tener que reconstruir todo desde memoria.</p><p><a href="https://github.com/Chudroy/csv-importer/tree/main/docs/architecture/adr">Los ADRs</a> hicieron otra cosa igual de importante: empaquetaron contexto. Si necesitaba razonar con un LLM sobre <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0007-add-broker-managed-retries-dead-letter-queues-and-a-recovery-ledger.md">retries, DLQs</a>, <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0005-use-a-transactional-outbox-for-api-job-acceptance.md">outbox</a>, <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0009-adopt-service-owned-schemas-and-payload-carrying-parser-handoffs.md">ownership de schemas</a> o <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0008-add-postgres-backed-operator-recovery-inspection-and-replay.md">recuperación operativa</a>, podía pasarle las decisiones relevantes y arrancar desde un punto mucho más útil. La documentación actuaba como memoria compartida.</p><p>Structurizr aportó un punto de entrada visual. Tener C4 y una descripción formal de contenedores, relaciones y límites me ayudaba a comprobar si la implementación seguía pareciéndose a la arquitectura escrita. Además, para aterrizar en el proyecto, empezar por el diagrama exige menos carga cognitiva que abrir varias docs y saltar al código.</p><p>En este proyecto, escribir documentos fue una forma de mantener el sistema bajo control.</p><h3>El roadmap cambió mi forma de trabajar con IA</h3><p>Paritendo del roadmap, el flujo acabó tomando una forma bastante estable:</p><ol><li>Diseñar una fase del roadmap.</li><li>Pedir análisis para implementarla.</li><li>Hacer preguntas y cerrar decisiones técnicas o arquitectónicas.</li><li>Generar un plan con las skills relevantes.</li><li>Implementar con coding agéntico.</li><li>Revisar con una skill de code review.</li><li>Corregir problemas.</li><li>Repetir revisión y corrección hasta que el resultado fuese razonable.</li><li>Revisar manualmente, hacer preguntas sobre la implementación y commitear.</li></ol><p>Se parecía a actuar como arquitecto de software dentro de un equipo pequeño. Yo ponía el énfasis en la especificación, las decisiones y las preguntas. El agente empujaba gran parte de la implementación. Después venían los tests, el review y las correcciones.</p><p>Ese flujo mejora mucho cuando el contexto está escrito. Con roadmap, ADRs y docs de runtime, el agente recibe algo más parecido a una dirección técnica. Sin esa base, la velocidad sigue estando ahí, pero se vuelve más fácil acabar con código que resuelve una interpretación distinta del sistema.</p><p>El cuello de botella se movió. Antes pensaba más en quién iba a escribir las líneas. Ahora pienso más en quién define con precisión el sistema que hay que construir.</p><h3>La infraestructura compartida se llevó gran parte del esfuerzo</h3><p>La implementación de servicios concretos resultó menos costosa que el terreno que había que preparar para que esos servicios convivieran.</p><p>Antes de que el flujo end-to-end tuviera interés, había que diseñar y construir unas cuantas piezas poco vistosas:</p><ul><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">contratos de mensajes</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">validación en los bordes del broker</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0002-use-structured-json-logs-and-correlation-ids.md">logs JSON estructurados</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0002-use-structured-json-logs-and-correlation-ids.md">correlation IDs</a>;</li><li>convenciones de configuración;</li><li>health checks;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0003-use-flyway-for-shared-postgres-schema-migrations.md">migraciones con Flyway</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0005-use-a-transactional-outbox-for-api-job-acceptance.md">outbox transaccional</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">topología RabbitMQ</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0007-add-broker-managed-retries-dead-letter-queues-and-a-recovery-ledger.md">retries, DLQs y ledger de recuperación</a>;</li><li>scripts de seed, inspección y recuperación.</li></ul><p>Cuando esas piezas estuvieron en su sitio, añadir comportamiento de dominio fue mucho más directo. También quedó más claro dónde se acumulaba la complejidad.</p><p>En arquitectura distribuida, el código de negocio viaja acompañado. Contratos, colas, estados persistidos, logs, scripts y herramientas de recuperación forman parte de la experiencia de desarrollar y operar el sistema.</p><h3>Tests, observabilidad y docs importan más que nunca</h3><p>En un monolito pequeño puedes razonar mucho desde el código. Aquí esa estrategia se agotó pronto.</p><p>El flujo cruza servicios, colas, tablas, outboxes y estados de recuperación. Si algo falla, necesitas seguir el camino completo: qué mensaje se publicó, qué consumidor lo recibió, si entró en retry, si terminó en DLQ, qué persistió PostgreSQL y qué estado expone el API público.</p><p>Por eso los tests y la observabilidad ganaron peso.</p><p>Los tests de contratos verifican que los mensajes se publican y consumen por RabbitMQ. Los tests end-to-end cubren el happy path, CSV malformado, fallo parcial por fila, duplicados, recuperación por retry, agotamiento hasta DLQ y fallos permanentes de negocio. Los scripts de inspección permiten mirar jobs, filas parseadas, outcomes y estado de recuperación sin improvisar SQL cada vez.</p><p>El stack de <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/observability-profile.md">observabilidad local</a> con <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0006-use-a-local-grafana-alloy-loki-and-grafana-stack-for-log-navigation.md">Grafana, Alloy y Loki</a> fue especialmente útil. Los servicios escriben logs JSON a stdout, Alloy los recoge desde Docker, Loki los indexa y Grafana permite navegarlos. Primero filtro por service, event o level; después bajo a correlation_id, import_job_id o message_id cuando quiero seguir una ejecución concreta.</p><p>También ayudaron los profiles de Docker Compose. Con tantos procesos en juego, poder levantar el stack base, la observabilidad o un grupo de servicios concreto reduce bastante fricción.</p><h3>Una sola persona con IA sigue pagando el coste del contexto</h3><p>La parte más dura del experimento fue asumir la velocidad de crecimiento del repositorio. Una persona con IA puede generar mucho código, pero entenderlo todo lleva otro ritmo.</p><p>Cada fase del roadmap podía añadir o modificar miles de líneas. Aunque la implementación fuese buena, seguía existiendo una deuda cognitiva: entender el diseño, revisar cambios, validar invariantes, comprobar cobertura de tests y mantener la documentación al día.</p><p>Mi impresión es que, para sentirme completamente dueño del código producido, habría necesitado entre 1.5x y 2x el tiempo invertido en el desarrollo agéntico. Revisar un sistema distribuido obliga a reconstruir muchos caminos de ejecución: mensajes duplicados, fallos parciales, retries, estados persistidos, lecturas públicas, idempotencia.</p><p>También aparece una tensión de rol. Como arquitecto, quieres proteger límites, contratos y decisiones. Como desarrollador, necesitas bajar al detalle de implementaciones, errores y edge cases. En sistemas distribuidos, esas dos responsabilidades compiten por tu atención.</p><p>La IA acelera la producción. El ownership sigue siendo tuyo.</p><h3>El tamaño llegó muy rápido</h3><p>El 10 de abril de 2026 me paré a mirar cuánto había crecido el repositorio. Me quedo con la lectura general: el tamaño ya empezaba a cambiar la forma de trabajar.</p><p>En unas tres semanas, csv-importer había alcanzado una escala suficiente para que el código dejara de ser el único centro de gravedad. Ya había varios servicios, lenguajes distintos, SQL, Docker, scripts, diagramas, documentación, tests y configuración operativa.</p><p>Ese crecimiento cambia la forma de trabajar. Puedes seguir añadiendo código, pero tu modelo mental empieza a quedarse atrás si no hay artefactos que lo sostengan. El roadmap, los ADRs, Structurizr, los tests y la observabilidad sirvieron precisamente para eso: mantener el sistema navegable mientras crecía.</p><h3>Lo que haría distinto</h3><p>Mantendría el experimento tal cual, porque el objetivo era aprender arquitectura distribuida. Para un producto de producción, lo enfocaría de otra manera.</p><p>Empezaría por un monolito modular salvo que hubiese una razón clara para separar procesos. RabbitMQ, DLQs, outbox, recuperación y observabilidad distribuida son herramientas potentes, con coste operativo y mental.</p><p>Definiría antes el escenario productivo concreto: tamaño máximo de CSV, número de filas, concurrencia esperada, latencia aceptable, operaciones de recuperación y criterios de éxito. Sin esos límites, es fácil diseñar “por arquitectura” en vez de diseñar para un problema concreto.</p><p>Mantendría, eso sí, la inversión inicial en especificación. El <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/runtime.md">runtime actual</a>, el roadmap, <a href="https://github.com/Chudroy/csv-importer/tree/main/docs/architecture/adr">los ADRs</a> y los scripts de verificación hicieron que el proyecto fuese navegable. En un flujo con IA, esa inversión actúa como control de calidad.</p><p>También trataría la revisión manual como una fase formal. Cuando el agente produce mucho código, revisar diffs se queda corto. Hay que preguntar por invariantes, estados imposibles, duplicados, idempotencia, fallos parciales y rutas de recuperación.</p><h3>Mis conclusiones</h3><p>La arquitectura por adelantado puede aumentar la velocidad si se mantiene pegada al proyecto. En este caso, el design doc y el roadmap me permitieron cambiar de contexto con menos coste y delegar implementaciones con más precisión.</p><p>Los LLMs hacen que la especificación pese más. Si un agente puede escribir miles de líneas en un día, la pregunta importante pasa a ser otra: si la petición describe exactamente el sistema que quieres construir.</p><p>Todo lo que rodea al código gana importancia: documentación, tests, observabilidad, ADRs, diagramas, scripts de inspección y herramientas de recuperación. En un sistema distribuido, esas piezas separan una demo vistosa de un proyecto que puedes entender cuando falla.</p><p>La arquitectura distribuida, o una arquitectura complicada cualquiera, sigue siendo difícil con IA. Quizá más difícil de gestionar, precisamente porque la velocidad de generación puede esconder el coste de comprensión.</p><p>El coding agéntico moderno comoditiza parte de la implementación. La responsabilidad de diseñar bien queda donde estaba. El trabajo de ingeniería se desplaza hacia especificar mejor, revisar mejor y construir sistemas que sigan siendo comprensibles cuando el volumen de código deja de ser el factor limitante.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=224366c957ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Systems Are Still Hard, Even with AI]]></title>
            <link>https://medium.com/@nijotigajo/what-i-learned-building-a-distributed-csv-importer-with-ai-7082fa63abc0?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/7082fa63abc0</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 14:57:32 GMT</pubDate>
            <atom:updated>2026-04-14T15:06:24.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kzqaEcVIpAhNEpze" /><figcaption>Photo by <a href="https://unsplash.com/@jaredmurray?utm_source=medium&amp;utm_medium=referral">Jared Murray</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On March 20, 2026, I started this project as an architecture exercise. The idea looked contained: import customers from CSV, process the file in the background, and record the result for each row.</p><p>Three weeks later, on April 10, 2026, the repository already had four services, RabbitMQ, PostgreSQL, Flyway, Structurizr, structured logs, a local stack with Grafana, Alloy, and Loki, DLQ-based recovery, and a first operator dashboard.</p><p>That speed of growth left me with a clear feeling. With AI, you can produce a lot of code in very little time. The delicate part comes afterward: defining the system well, preserving the architecture, and still understanding what has been built.</p><p>This post-mortem captures those lessons. For a TL;DR, the conclusions are at the end.</p><p><a href="https://github.com/Chudroy/csv-importer">Link to Github repo</a>.</p><h3>Microservices as a training field</h3><p>The application imports customer records from CSV. A user uploads a file, the system creates a job, processes the content asynchronously, normalizes rows, creates or updates customers, and exposes a summary with rows created, updated, failed, or ignored.</p><p>If I had needed to maintain this as a product, my starting point would have been a modular monolith. The <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/design-doc.md">design document</a> says this explicitly: the distributed architecture was chosen for learning, not because it was the shortest path.</p><p>I wanted to practice service boundaries, asynchronous workflows, message contracts, idempotency, partial failures, observability, and operational recovery. The current result is split across four services:</p><ul><li>api-service, as the public HTTP edge.</li><li>import-service, as the owner of import state, reads, and recovery.</li><li>parser-service, written in Rust, as the owner of CSV parsing and normalization.</li><li>customer-service, as the owner of customer data and email-based reconciliation in v1.</li></ul><p>RabbitMQ transports messages. PostgreSQL stores durable state. Flyway applies migrations, Structurizr documents the architecture, and Docker Compose starts the local environment.</p><p>As an exercise, it worked very well. As the baseline architecture for a small system, it would have been an expensive choice.</p><p>The lesson fits Martin Fowler’s <a href="https://martinfowler.com/bliki/MonolithFirst.html">MonolithFirst</a>: it is worth delaying distribution until you have a strong reason to pay for it. A bad boundary between services implies contracts, persistence, messages, tests, observability, and recovery. Refactoring stops being a local change.</p><h3>Writing docs to think</h3><p>The most valuable thing at the beginning was writing architecture down.</p><p>The first important artifact was the <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/design-doc.md">design document</a>. That is where I fixed the purpose, scope, functional and non-functional requirements, quality attributes, and v1 decisions: asynchronous processing, RabbitMQ, PostgreSQL, storage for parsed rows, email matching, and row-level result visibility.</p><p>Then came the <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/roadmap.md">roadmap</a>. Over time, it became the backbone of the project. Each phase had a goal, features, and a definition of done. When I came back to the repo after several days, that document gave me the thread again without forcing me to rebuild everything from memory.</p><p>The <a href="https://github.com/Chudroy/csv-importer/tree/main/docs/architecture/adr">ADRs</a> did something just as important: they packaged context. If I needed to reason with an LLM about <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0007-add-broker-managed-retries-dead-letter-queues-and-a-recovery-ledger.md">retries, DLQs</a>, <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0005-use-a-transactional-outbox-for-api-job-acceptance.md">outbox</a>, <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0009-adopt-service-owned-schemas-and-payload-carrying-parser-handoffs.md">schema ownership</a>, or <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0008-add-postgres-backed-operator-recovery-inspection-and-replay.md">operational recovery</a>, I could pass the relevant decisions and start from a much more useful place. Documentation acted as shared memory.</p><p>Structurizr provided a visual entry point. Having C4 diagrams and a formal description of containers, relationships, and boundaries helped me check whether the implementation still resembled the written architecture. It also lowered the cognitive load for landing in the project: starting from the diagram was easier than opening several docs and jumping straight into the code.</p><p>In this project, writing documents was a way to keep the system under control.</p><h3>The roadmap changed how I worked with AI</h3><p>Starting from the roadmap, the workflow eventually became fairly stable:</p><ol><li>Design a roadmap phase.</li><li>Ask for analysis before implementation.</li><li>Ask questions and close technical or architectural decisions.</li><li>Generate a plan using the relevant skills.</li><li>Implement with agentic coding.</li><li>Review with a code review skill.</li><li>Fix problems.</li><li>Repeat review and correction until the result was reasonable.</li><li>Review manually, ask questions about the implementation, and commit the changes.</li></ol><p>It felt similar to acting as a software architect inside a small team. I focused on the specification, the decisions, and the questions. The agent pushed much of the implementation. Then came tests, review, and corrections.</p><p>That workflow improves a lot when the context is written down. With a roadmap, ADRs, and runtime docs, the agent receives something closer to technical direction. Without that foundation, the speed is still there, but it becomes easier to end up with code that solves a different interpretation of the system.</p><p>The bottleneck moved. Before, I thought more about who would write the lines. Now I think more about who defines the system to be built with enough precision.</p><h3>Shared infrastructure took much of the effort</h3><p>Implementing specific services was less expensive than preparing the ground those services needed in order to coexist.</p><p>Before the end-to-end flow became interesting, I had to design and build several less visible pieces:</p><ul><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">message contracts</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">validation at broker boundaries</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0002-use-structured-json-logs-and-correlation-ids.md">structured JSON logs</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0002-use-structured-json-logs-and-correlation-ids.md">correlation IDs</a>;</li><li>configuration conventions;</li><li>health checks;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0003-use-flyway-for-shared-postgres-schema-migrations.md">Flyway migrations</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0005-use-a-transactional-outbox-for-api-job-acceptance.md">transactional outbox</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0004-use-a-shared-rabbitmq-topology-and-contract-validation-at-broker-boundaries.md">RabbitMQ topology</a>;</li><li><a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0007-add-broker-managed-retries-dead-letter-queues-and-a-recovery-ledger.md">retries, DLQs, and recovery ledger</a>;</li><li>seed, inspection, and recovery scripts.</li></ul><p>Once those pieces were in place, adding domain behavior became much more direct. It also became clearer where the complexity was accumulating.</p><p>In distributed architecture, business code travels with an entourage. Contracts, queues, persisted states, logs, scripts, and recovery tools all become part of the experience of developing and operating the system.</p><h3>Tests, observability, and docs matter more than ever</h3><p>In a small monolith, you can reason a lot from the code. Here, that strategy ran out quickly.</p><p>The flow crosses services, queues, tables, outboxes, and recovery states. If something fails, you need to follow the whole path: which message was published, which consumer received it, whether it entered retry, whether it ended up in the DLQ, what PostgreSQL persisted, and what state the public API exposes.</p><p>That is why tests and observability became more important.</p><p>Contract tests verify that messages are published to and consumed from RabbitMQ. End-to-end tests cover the happy path, malformed CSV, partial row failure, duplicates, retry recovery, exhaustion into DLQ, and permanent business failures. Inspection scripts let me look at jobs, parsed rows, outcomes, and recovery state without improvising SQL every time.</p><p>The <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/observability-profile.md">local observability</a> stack with <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/adr/0006-use-a-local-grafana-alloy-loki-and-grafana-stack-for-log-navigation.md">Grafana, Alloy, and Loki</a> was especially useful. The services write JSON logs to stdout, Alloy collects them from Docker, Loki indexes them, and Grafana makes them navigable. I first filter by service, event, or level; then I go down to correlation_id, import_job_id, or message_id when I want to follow one specific execution.</p><p>Docker Compose profiles also helped. With so many processes in play, being able to start the base stack, observability, or a specific group of services reduces friction substantially.</p><h3>One person with AI still pays the context cost</h3><p>The hardest part of the experiment was absorbing the repository’s growth speed. One person with AI can generate a lot of code, but understanding all of it moves at a different pace.</p><p>Each roadmap phase could add or modify thousands of lines. Even when the implementation was good, there was still cognitive debt: understanding the design, reviewing changes, validating invariants, checking test coverage, and keeping documentation up to date.</p><p>My impression is that, to feel fully in control of the code produced, I would have needed between 1.5x and 2x the time spent on agentic development. Reviewing a distributed system forces you to reconstruct many execution paths: duplicate messages, partial failures, retries, persisted states, public reads, and idempotency.</p><p>There is also a role tension. As an architect, you want to protect boundaries, contracts, and decisions. As a developer, you need to go down into implementation details, errors, and edge cases. In distributed systems, those two responsibilities compete for your attention.</p><p>AI accelerates production. Ownership remains yours.</p><h3>The size arrived very quickly</h3><p>On April 10, 2026, I stopped to look at how much the repository had grown. What stays with me is the general reading: the size was already starting to change how I worked.</p><p>In about three weeks, csv-importer had reached enough scale for code to stop being the only center of gravity. There were already several services, different languages, SQL, Docker, scripts, diagrams, documentation, tests, and operational configuration.</p><p>That growth changes the work. You can keep adding code, but your mental model starts falling behind if there are no artifacts to support it. The roadmap, ADRs, Structurizr, tests, and observability served exactly that purpose: keeping the system navigable as it grew.</p><h3>What I would do differently</h3><p>I would keep the experiment as it was, because the goal was to learn distributed architecture. For a production product, I would approach it differently.</p><p>I would start with a modular monolith unless there was a clear reason to split processes. RabbitMQ, DLQs, outbox, recovery, and distributed observability are powerful tools, with operational and mental cost.</p><p>I would define the concrete production scenario earlier: maximum CSV size, number of rows, expected concurrency, acceptable latency, recovery operations, and success criteria. Without those limits, it is easy to design “for architecture” instead of designing for a concrete problem.</p><p>I would still keep the initial investment in specification. The <a href="https://github.com/Chudroy/csv-importer/blob/main/docs/architecture/runtime.md">current runtime</a>, the roadmap, <a href="https://github.com/Chudroy/csv-importer/tree/main/docs/architecture/adr">ADRs</a>, and verification scripts made the project navigable. In an AI workflow, that investment acts as quality control.</p><p>I would also treat manual review as a formal phase. When the agent produces a lot of code, reviewing diffs is not enough. You need to ask about invariants, impossible states, duplicates, idempotency, partial failures, and recovery paths.</p><h3>My conclusions</h3><p>Up-front architecture can increase speed if it stays attached to the project. In this case, the design doc and roadmap let me switch context with less cost and delegate implementations with more precision.</p><p>LLMs make specification matter more. If an agent can write thousands of lines in a day, the important question changes: does the request describe exactly the system you want to build?</p><p>Everything around the code becomes more important: documentation, tests, observability, ADRs, diagrams, inspection scripts, and recovery tools. In a distributed system, those pieces separate an impressive demo from a project you can understand when it fails.</p><p>Distributed architecture, or any complicated architecture, is still difficult with AI. It may even be harder to manage, precisely because generation speed can hide the cost of understanding.</p><p>Modern agentic coding commoditizes part of implementation. The responsibility for good design stays where it was. Engineering work shifts toward specifying better, reviewing better, and building systems that remain understandable when code volume stops being the limiting factor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7082fa63abc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When your client’s VPN eats your Docker network — my diagnosis and solution]]></title>
            <link>https://medium.com/@nijotigajo/when-your-clients-vpn-eats-your-docker-network-my-diagnosis-and-solution-57f12543b4f7?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/57f12543b4f7</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 17:07:09 GMT</pubDate>
            <atom:updated>2025-12-09T17:07:09.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>When your client’s VPN eats your Docker network — my diagnosis and solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gmDG-nE8tCeelvWA" /><figcaption>Photo by <a href="https://unsplash.com/@mikedoherty?utm_source=medium&amp;utm_medium=referral">Mike Doherty</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Quick note: this is not an introduction to Docker or networking. I assume a linux environment, and that you already know about subnets, </em><em>docker inspect, </em><em>docker compose, and </em><em>ip route.</em></blockquote><p>Context: I’m developing an application that uses Docker, with a PostgreSQL database in a container (let’s call it app-db). To access a client resource I need to connect to a corporate VPN using Cisco AnyConnect.</p><p>For months everything worked fine. Until, from one day to the next:</p><ul><li>With the VPN disconnected, docker compose up and psql against localhost:5432 work normally.</li><li>With the VPN connected, the database stops responding from the host, both from psql and from DBeaver.</li><li>Inside the container, the database is still alive.</li><li>The container logs show no errors, they just never receive the connection.</li></ul><p>So the problem wasn’t Postgres, it was the path leading to it.</p><p>What I describe here is how I pulled the thread, what commands I used, and the final fix: moving Docker’s default network range to 172.30.0.0/16 with /24 blocks.</p><h3>The Symptom: Docker Works Until I Turn On the VPN</h3><p>The pattern was very clear:</p><ul><li>VPN off: psql &quot;postgresql://user@localhost:5432/user&quot; -c &#39;select 1;&#39; returns 1 without any issue.</li><li>VPN on: the same command hangs until it times out.</li></ul><p>The app-db container is healthy, so the next step was to look at its IP and the Docker network it uses.</p><h3>Step 1: Inspect the Container IP and Its Network</h3><p>First, the container’s internal IP:</p><pre>docker inspect app-db \<br>  --format &#39;{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39;</pre><p>Output:</p><pre>172.20.0.2</pre><p>Now I want to know which Docker network it’s attached to and what gateway that network uses. I run:</p><pre>docker inspect app-db \<br>  --format &#39;{{json .NetworkSettings.Networks}}&#39;</pre><p>Relevant output (simplified):</p><pre>{<br>  &quot;app-backend-tier&quot;: {<br>    &quot;Gateway&quot;: &quot;172.20.0.1&quot;,<br>    &quot;IPAddress&quot;: &quot;172.20.0.2&quot;,<br>    &quot;IPPrefixLen&quot;: 16<br>  }<br>}</pre><p>And to wrap it up:</p><pre>docker network inspect app-backend-tier \<br>  --format &#39;{{json .IPAM.Config}}&#39;</pre><p>Output:</p><pre>[{&quot;Subnet&quot;:&quot;172.20.0.0/16&quot;,&quot;Gateway&quot;:&quot;172.20.0.1&quot;}]</pre><p>Summary:</p><ul><li>My Docker backend network is called app-backend-tier.</li><li>It uses the subnet 172.20.0.0/16.</li><li>The host, within that network, has the IP 172.20.0.1.</li><li>The app-db container has 172.20.0.2 and uses 172.20.0.1 as its gateway.</li></ul><p>So far, everything checks out.</p><h3>Step 2: Ask Linux Where It’s Sending the Packets</h3><p>The key question is: “If I want to talk to 172.20.0.2, which interface will the traffic take”</p><p>You can see that with:</p><pre>ip route get 172.20.0.2</pre><p>First, with the VPN off:</p><pre>172.20.0.2 dev br-1227e707db3e src 172.20.0.1 uid 1000<br>    cache</pre><p>Interpretation:</p><ul><li>To reach 172.20.0.2, the kernel uses interface br-1227e707db3e, the Docker bridge associated with app-backend-tier.</li><li>The packet’s source IP is 172.20.0.1, which matches the bridge’s IP in that network.</li></ul><p>Perfect, traffic is going where it should.</p><p>Now I repeat the command with the client VPN active:</p><pre>172.20.0.2 dev cscotun0 src 10.11.5.238 uid 1000<br>    cache</pre><p>This is where everything goes wrong:</p><ul><li>Instead of using the Docker bridge, the kernel chooses interface cscotun0, the VPN tunnel.</li><li>The source IP is now 10.11.5.238, the internal address assigned by the VPN.</li></ul><p>In short: when I turn on the VPN, my machine thinks the container 172.20.0.2 lives behind the corporate tunnel, not inside Docker.</p><h3>Step 3: Check What Routes the VPN Injected</h3><p>I want to see what routes exist for that subnet. With the VPN connected:</p><pre>ip -4 route | grep 172.20.0.0/16</pre><p>Output:</p><pre>172.20.0.0/16 dev cscotun0 proto unspec scope link<br>172.20.0.0/16 dev br-1227e707db3e proto kernel scope link src 172.20.0.1</pre><p>So I now have two identical routes for the same subnet:</p><ul><li>The VPN announces 172.20.0.0/16 through cscotun0.</li><li>Docker uses 172.20.0.0/16 on the Docker bridge.</li></ul><p>Two networks claiming the same private block.</p><p>Linux doesn’t know anything about “this is Docker” or “this is corporate infrastructure”. It just sees two routes for the same prefix and, when the VPN is on, chooses cscotun0, exactly the opposite of what I want.</p><p>Concrete result:</p><ul><li>When docker-proxy tries to talk to 172.20.0.2:5432, the SYN goes through the VPN with source 10.11.5.238.</li><li>That packet is lost in the corporate network, so the container never sees it.</li><li>From my perspective, the database “crashes” the moment I turn on the VPN.</li></ul><h3>Step 4: Confirm with ss and tcpdump</h3><p>While psql was hanging, I checked the TCP connections:</p><pre>sudo ss -ntp | grep 5432</pre><p>Something like:</p><pre>ESTAB      127.0.0.1:41738   127.0.0.1:5432   users:((&quot;psql&quot;,pid=...),(&quot;docker-proxy&quot;,pid=...))<br>SYN-SENT   10.11.5.238:35082 172.20.0.2:5432 users:((&quot;docker-proxy&quot;,pid=...))</pre><p>What’s happening:</p><ul><li>psql talks correctly to docker-proxy on 127.0.0.1:5432.</li><li>It’s docker-proxy that tries to open a connection to 172.20.0.2:5432, but with source 10.11.5.238 and through cscotun0.</li></ul><p>With tcpdump, it becomes completely obvious:</p><pre>sudo tcpdump -n -i any host 172.20.0.2 and port 5432</pre><p>You see SYN packets going out through cscotun0.</p><p>If you filter on the Docker bridge:</p><pre>sudo tcpdump -n -i br-1227e707db3e host 172.20.0.2 and port 5432</pre><p>nothing appears while the client hangs.</p><p>So it’s confirmed: the VPN took over the 172.20.0.0/16 range and left Docker stranded.</p><h3>Step 5: Change Docker’s Default Address Pools</h3><p>At this point, the options are:</p><ul><li>Ask the client to change their VPN so it doesn’t announce a huge block like 172.20.0.0/16.</li><li>Or move Docker to a range the VPN doesn’t use and that I control.</li></ul><p>To keep working today, the second option was the only viable one.</p><p>The idea:</p><ul><li>Stop using 172.20.0.0/16 for my Docker networks.</li><li>Reserve a private range just for Docker, like 172.30.0.0/16.</li><li>Make Docker allocate smaller /24 slices from that block each time it creates a network.</li></ul><p>That’s configured in /etc/docker/daemon.json. Mine ended up like this:</p><pre>{<br>  &quot;default-address-pools&quot;: [<br>    {<br>      &quot;base&quot;: &quot;172.30.0.0/16&quot;,<br>      &quot;size&quot;: 24<br>    }<br>  ]<br>}</pre><p>This tells Docker:</p><ul><li>Use 172.30.0.0/16 as the pool for new bridge networks.</li><li>Assign a /24 subnet to each new network.</li></ul><p>In practice, Docker will create networks like:</p><ul><li>172.30.0.0/24</li><li>172.30.1.0/24</li><li>172.30.2.0/24</li></ul><p>each with its own bridge br-xxxx and gateway 172.30.x.1.</p><h3>Apply the Change</h3><p>After editing daemon.json, I ran:</p><pre>sudo systemctl restart docker</pre><pre>docker network prune<br>docker compose down<br>docker compose up -d</pre><p>Then I checked the routes:</p><pre>ip -4 route | grep -E &quot;(docker0|br-)&quot;</pre><p>Actual output:</p><pre>172.30.0.0/24 dev docker0 proto kernel scope link src 172.30.0.1 linkdown <br>172.30.1.0/24 dev br-8884bae1cbb0 proto kernel scope link src 172.30.1.1 <br>172.30.2.0/24 dev br-10bf1d5c2043 proto kernel scope link src 172.30.2.1</pre><p>Inspecting the database container again:</p><pre>docker inspect app-db \<br>  --format &#39;{{json .NetworkSettings.Networks}}&#39;</pre><p>Now it has an IP like 172.30.1.2.</p><p>The real test: with the VPN active:</p><pre>ip route get 172.30.1.2</pre><p>I get:</p><pre>172.30.1.2 dev br-8884bae1cbb0 src 172.30.1.1</pre><p>No sign of cscotun0.</p><p>From that point on, psql and DBeaver worked again with the VPN on.</p><h3>Lessons Learned</h3><p>A couple of takeaways if you run into something similar.</p><p><strong>1. A corporate VPN can break Docker without touching Docker</strong></p><p>If the VPN announces a wide private block like 172.20.0.0/16 and Docker happens to use that same range, you&#39;re in trouble. You think you&#39;re talking to your container, but your packets are heading into the client&#39;s network.</p><p><strong>2. </strong><strong>ip route get &lt;IP&gt; is your best friend</strong></p><p>Before you dig through container logs, ask the kernel:</p><pre>ip route get 172.20.0.2</pre><p>If you see dev br-..., good. If you see dev cscotun0 or anything odd, now you know why the connection never arrives.</p><p><strong>3. You will eventually need to control Docker’s address ranges</strong></p><p>Letting Docker auto assign private subnets works until you run into a VPN, a Kubernetes cluster, or anything else living in 172.16.0.0/12. Setting default-address-pools avoids surprises.</p><p><strong>4. The “correct” theoretical solution is not always viable</strong></p><p>In an ideal world, the VPN would only announce what it needs, not a full /16. But I don&#39;t control that. What I do control is what ranges Docker uses.</p><p>Moving Docker to 172.30.0.0/16 with /24 networks gave me my workspace back without depending on anyone else.</p><p>If you’re reading this because you turned on a VPN and suddenly access to localhost vanished, here&#39;s the minimum recipe:</p><ol><li>Get the container IP with docker inspect.</li><li>Check the network subnet and gateway with docker network inspect.</li><li>Compare with the VPN routes using ip -4 route and ip route get &lt;DB_IP&gt;.</li><li>If there’s a collision, define default-address-pools in /etc/docker/daemon.json, restart Docker, and recreate the networks.</li></ol><p>From there, your little Docker universe goes back to being separated from the client’s network universe, and everything stays in its place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57f12543b4f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cuando el VPN de tu cliente se come tu red de Docker — cómo lo he diagnosticado y resuelto]]></title>
            <link>https://medium.com/@nijotigajo/cuando-el-vpn-de-tu-cliente-se-come-tu-red-de-docker-c%C3%B3mo-lo-he-diagnosticado-y-resuelto-28fdc96b1e7e?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/28fdc96b1e7e</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 17:07:07 GMT</pubDate>
            <atom:updated>2025-12-09T17:07:07.249Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Cuando el VPN de tu cliente se come tu red de Docker — cómo lo he diagnosticado y resuelto</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e5eWXDgduPZUGAii" /><figcaption>Photo by <a href="https://unsplash.com/@mikedoherty?utm_source=medium&amp;utm_medium=referral">Mike Doherty</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Aviso rápido: esto no es una introducción a Docker ni a redes. Asumo un entorno de linux, y un conocimiento sobre subredes, </em><em>docker inspect, </em><em>docker compose y </em><em>ip route.</em></blockquote><p>Contexto: estoy desarrollando una aplicación que usa Docker, con una base de datos PostgreSQL en un contenedor (llamémoslo app-db). Para acceder a un recurso del cliente tengo que conectarme a un VPN corporativo usando Cisco AnyConnect.</p><p>Durante meses todo ha ido bien. Hasta que, de un día para otro:</p><ul><li>Con el VPN desconectado, docker compose up y psql contra localhost:5432 funcionan sin más.</li><li>Con el VPN conectado, la base de datos deja de responder desde el host, tanto desde psql como desde DBeaver.</li><li>Dentro del contenedor, la base de datos sigue viva.</li><li>Los logs del contenedor no muestran errores, simplemente nunca reciben la conexión.</li></ul><p>Es decir, el problema no estaba en Postgres, estaba en el camino hasta él.</p><p>Lo que cuento aquí es cómo he ido tirando del hilo, qué comandos he usado y la solución final: mover el rango por defecto de redes de Docker a 172.30.0.0/16 con bloques de tamaño /24.</p><h3>El síntoma: Docker funciona, hasta que enciendo el VPN</h3><p>El patrón ha sido muy claro:</p><ul><li>VPN apagado: psql &quot;postgresql://usuario@localhost:5432/usuario&quot; -c &#39;select 1;&#39; devuelve 1 sin problema.</li><li>VPN encendido: el mismo comando se queda colgado hasta que hace timeout.</li></ul><p>El contenedor app-db está sano, así que el siguiente paso ha sido mirar qué IP tiene y qué red de Docker está usando.</p><h3>Paso 1: inspeccionar la IP del contenedor y su red</h3><p>Primero, la IP interna del contenedor:</p><pre>docker inspect app-db \<br>  --format &#39;{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39;</pre><p>Salida:</p><pre>172.20.0.2</pre><p>Ahora quiero saber a qué red de Docker está enchufado y cuál es la puerta de enlace de esa red. Uso:</p><pre>docker inspect app-db \<br>  --format &#39;{{json .NetworkSettings.Networks}}&#39;</pre><p>Salida relevante (simplificada):</p><pre>{<br>  &quot;app-backend-tier&quot;: {<br>    &quot;Gateway&quot;: &quot;172.20.0.1&quot;,<br>    &quot;IPAddress&quot;: &quot;172.20.0.2&quot;,<br>    &quot;IPPrefixLen&quot;: 16<br>  }<br>}</pre><p>Y rematar con:</p><pre>docker network inspect app-backend-tier \<br>  --format &#39;{{json .IPAM.Config}}&#39;</pre><p>Salida:</p><pre>[{&quot;Subnet&quot;:&quot;172.20.0.0/16&quot;,&quot;Gateway&quot;:&quot;172.20.0.1&quot;}]</pre><p>Resumen:</p><ul><li>Mi red de backend de Docker se llama app-backend-tier.</li><li>Usa la subred 172.20.0.0/16.</li><li>El host, en esa red, tiene IP 172.20.0.1.</li><li>El contenedor app-db tiene 172.20.0.2 y usa como gateway 172.20.0.1.</li></ul><p>Hasta aquí, todo bien.</p><h3>Paso 2: preguntarle a Linux por dónde saca los paquetes</h3><p>La pregunta clave es: “Si quiero hablar con 172.20.0.2, por qué interfaz se va a ir el tráfico”.</p><p>Eso se ve con:</p><pre>ip route get 172.20.0.2</pre><p>Primero, con el VPN apagado:</p><pre>172.20.0.2 dev br-1227e707db3e src 172.20.0.1 uid 1000<br>    cache</pre><p>Interpretación:</p><ul><li>Para llegar a 172.20.0.2, el kernel usa la interfaz br-1227e707db3e, que es el bridge de Docker asociado a app-backend-tier.</li><li>El paquete sale con IP de origen 172.20.0.1, que es justo la IP del bridge en esa red.</li></ul><p>Perfecto, el tráfico está yendo a la red correcta.</p><p>Ahora repito el comando con el VPN del cliente activado:</p><pre>172.20.0.2 dev cscotun0 src 10.11.5.238 uid 1000<br>    cache</pre><p>Y aquí se encienden todas las alarmas:</p><ul><li>En vez de usar el bridge de Docker, el kernel ha decidido usar la interfaz cscotun0, que es el túnel del VPN (AnyConnect).</li><li>La IP de origen ahora es 10.11.5.238, la IP interna que me da el VPN.</li></ul><p>Resumiendo: cuando enciendo el VPN, mi propio ordenador cree que el contenedor 172.20.0.2 vive detrás del túnel corporativo, no en la red de Docker.</p><h3>Paso 3: ver qué rutas ha metido el VPN en la tabla</h3><p>Quiero ver qué rutas existen para esa subred. Con el VPN conectado:</p><pre>ip -4 route | grep 172.20.0.0/16</pre><p>Salida:</p><pre>172.20.0.0/16 dev cscotun0 proto unspec scope link<br>172.20.0.0/16 dev br-1227e707db3e proto kernel scope link src 172.20.0.1</pre><p>O sea, tengo dos rutas idénticas para la misma subred:</p><ul><li>El VPN del cliente anuncia 172.20.0.0/16 a través de cscotun0.</li><li>Docker también está usando 172.20.0.0/16 en el bridge br-1227e707db3e.</li></ul><p>Dos redes reclamando el mismo bloque privado.</p><p>Linux no sabe nada de “esto es Docker” y “esto es infraestructura corporativa”. Solo ve dos rutas para el mismo prefijo y, en presencia del VPN, acaba eligiendo cscotun0, que es justo lo contrario de lo que quiero.</p><p>Resultado concreto:</p><ul><li>Cuando docker-proxy intenta hablar con 172.20.0.2:5432, el SYN sale por el VPN con origen 10.11.5.238.</li><li>Ese paquete se pierde por la red del cliente, y mi contenedor nunca llega a verlo.</li><li>Desde mi punto de vista, la base de datos “se ha caído” en cuanto enciendo el VPN.</li></ul><h3>Paso 4: confirmarlo con ss y tcpdump</h3><p>Mientras psql se quedaba pensando, he mirado las conexiones TCP:</p><pre>sudo ss -ntp | grep 5432</pre><p>Algo así:</p><pre>ESTAB      127.0.0.1:41738   127.0.0.1:5432   users:((&quot;psql&quot;,pid=...),(&quot;docker-proxy&quot;,pid=...))<br>SYN-SENT   10.11.5.238:35082 172.20.0.2:5432 users:((&quot;docker-proxy&quot;,pid=...))</pre><p>Lo que está pasando:</p><ul><li>psql habla bien con docker-proxy en 127.0.0.1:5432.</li><li>Es docker-proxy quien luego intenta abrir una conexión a 172.20.0.2:5432, pero lo hace con origen 10.11.5.238 y a través del túnel cscotun0.</li></ul><p>Con tcpdump se ve todavía más claro:</p><pre>sudo tcpdump -n -i any host 172.20.0.2 and port 5432</pre><p>Se ven SYN saliendo por cscotun0. En cambio, si filtro en el bridge de Docker:</p><pre>sudo tcpdump -n -i br-1227e707db3e host 172.20.0.2 and port 5432</pre><p>no aparece nada mientras el cliente está colgado.</p><p>Y así queda claro: el VPN se ha quedado con el rango 172.20.0.0/16 y ha dejado a Docker colgado.</p><h3>Paso 5: cambiar los rangos por defecto de Docker</h3><p>Llegados a este punto, opciones:</p><ul><li>Pedir al cliente que cambie su VPN para no anunciar un bloque tan bestia como 172.20.0.0/16.</li><li>O mover Docker a un rango que el VPN no use y que está bajo mi control.</li></ul><p>Para poder seguir currando hoy, la segunda opción ha sido la única realista.</p><p>La idea es:</p><ul><li>Dejar de usar 172.20.0.0/16 para mis redes de Docker.</li><li>Reservar un rango privado solo para Docker, por ejemplo 172.30.0.0/16.</li><li>Hacer que Docker, cada vez que cree una red nueva, coja un trozo más pequeño (un /24) dentro de ese bloque.</li></ul><p>Eso se configura en /etc/docker/daemon.json. En mi caso se ha quedado así:</p><pre>{<br>  &quot;default-address-pools&quot;: [<br>    {<br>      &quot;base&quot;: &quot;172.30.0.0/16&quot;,<br>      &quot;size&quot;: 24<br>    }<br>  ]<br>}</pre><p>Esto le dice a Docker:</p><ul><li>Usa 172.30.0.0/16 como “pool” para nuevas redes bridge.</li><li>Cada vez que crees una red, asígnale una subred /24 dentro de ese bloque (size: 24).</li></ul><p>En la práctica, las redes que vaya creando Docker tendrán subredes tipo:</p><ul><li>172.30.0.0/24</li><li>172.30.1.0/24</li><li>172.30.2.0/24</li></ul><p>y así sucesivamente, cada una con su bridge br-xxxx y su gateway 172.30.x.1.</p><h3>Aplicar el cambio</h3><p>Después de editar daemon.json, he hecho:</p><pre>sudo systemctl restart docker<br>docker network prune        # limpiar redes que no se usan<br>docker compose down         # en el proyecto<br>docker compose up -d        # recrear servicios y redes</pre><p>Luego he comprobado las rutas:</p><pre>ip -4 route | grep -E &quot;(docker0|br-)&quot;</pre><p>Salida real:</p><pre>172.30.0.0/24 dev docker0 proto kernel scope link src 172.30.0.1 linkdown <br>172.30.1.0/24 dev br-8884bae1cbb0 proto kernel scope link src 172.30.1.1 <br>172.30.2.0/24 dev br-10bf1d5c2043 proto kernel scope link src 172.30.2.1</pre><p>Y si inspecciono otra vez el contenedor de base de datos:</p><pre>docker inspect app-db \<br>  --format &#39;{{json .NetworkSettings.Networks}}&#39;</pre><p>veo que ahora tiene una IP tipo 172.30.1.2 dentro de una de esas redes nuevas.</p><p>La prueba de fuego: con el VPN conectado, vuelvo a preguntar:</p><pre>ip route get 172.30.1.2</pre><p>y ahora obtengo algo del estilo:</p><pre>172.30.1.2 dev br-8884bae1cbb0 src 172.30.1.1</pre><p>No hay rastro de cscotun0 en esa ruta. A partir de aquí, psql y DBeaver han vuelto a conectar sin pegas, incluso con el VPN del cliente activo.</p><h3>Lecciones que me llevo</h3><p>Un par de conclusiones por si te encuentras en algo parecido.</p><p><strong>1. Un VPN corporativo puede romperte Docker sin tocar Docker</strong></p><p>Si el VPN anuncia un bloque privado muy ancho, tipo 172.20.0.0/16, y Docker decide usar justo ese mismo rango para una red, tienes un choque de frente. Tú piensas que hablas con tu contenedor, pero tus paquetes se están yendo al túnel del cliente.</p><p><strong>2. </strong><strong>ip route get &lt;IP&gt; es tu mejor amigo</strong></p><p>Antes de volverte loco con logs de contenedores, pregúntale al kernel:</p><pre>ip route get 172.20.0.2</pre><p>Si ves dev br-..., bien. Si ves dev cscotun0 o cualquier otra interfaz rara, ya sabes por qué nunca llega la conexión.</p><p><strong>3. Tarde o temprano hay que tomar control de los rangos de Docker</strong></p><p>Dejar que Docker vaya eligiendo subredes privadas “a su bola” funciona, hasta que te cruzas con un VPN, un clúster de Kubernetes o cualquier cosa que también use 172.16.0.0/12. Configurar default-address-pools es una forma muy simple de evitar sorpresas.</p><p><strong>4. La solución “correcta” en teoría no siempre es la solución viable</strong></p><p>Lo ideal sería que el VPN del cliente anunciase solo lo que necesita, por ejemplo la IP o subred exacta del recurso al que tengo que acceder, en lugar de quedarse con todo 172.20.0.0/16. Pero yo no controlo esa configuración. Lo que sí controlo es qué rangos usa Docker en mi máquina.</p><p>Mover Docker a 172.30.0.0/16 con redes /24 me ha devuelto la paz sin depender de nadie.</p><p>Si estás leyendo esto porque enciendes un VPN y de repente localhost deja de existir, mi receta mínima sería:</p><ol><li>Saca la IP del contenedor con docker inspect.</li><li>Mira qué subred y gateway usa esa red con docker network inspect.</li><li>Compara con lo que anuncia el VPN con ip -4 route y ip route get &lt;DB_IP&gt;.</li><li>Si hay colisión, define default-address-pools en /etc/docker/daemon.json en un rango que el VPN no use, reinicia Docker y recrea las redes.</li></ol><p>A partir de ahí, ya vuelves a tener tu pequeño universo Docker separado del universo de redes del cliente, y cada uno en su sitio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28fdc96b1e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Series: Structuring Libraries in Nx + Angular — Part 2 · Library types within a subdomain]]></title>
            <link>https://medium.com/@nijotigajo/series-structuring-libraries-in-nx-angular-part-2-library-types-within-a-subdomain-98fac2fdb64c?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/98fac2fdb64c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 13:20:57 GMT</pubDate>
            <atom:updated>2025-11-12T13:21:10.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EBPa-7IFQDaRBlsK" /><figcaption>Photo by <a href="https://unsplash.com/@tothnorex?utm_source=medium&amp;utm_medium=referral">Norbert Tóth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This installment picks up right where Part 1 left off. There we set the common ground: ubiquitous language, domains and <strong>subdomains</strong>, and we agreed the repository structure should tell the story of the business at a glance. If that was the map, here we get on the ground: how that map takes shape inside libs/ and what boundaries keep things coherent as the project grows. Although the focus is Nx + Angular, 99% transfers to other stacks.</p><p>We’ll work with a short but sufficient catalogue of library types per <strong>subdomain</strong>: feature, data-access (or domain), ui, and utils, with actions as optional when state is modeled by events. We’ll cover the responsibility of each one, how they collaborate, and which dependencies to maintain so the graph stays readable. We’ll also place state: what belongs to the view (feature) and what is cross-cutting to the domain (data-access).</p><p>We’ll close with practical criteria to decide <strong>when to create a library</strong> and <strong>when to extract to </strong>shared prefer generic only when it adds value in more than one place—don’t force it or sacrifice clarity. The idea is that when the discount rule changes, you know exactly which door to knock on and the change is encapsulated by meaning.</p><blockquote>I’ve added a TL;DR to the longer sections for those who’d prefer a summary or already know about that concept.</blockquote><h3>Catalogue of library types and their role</h3><p>This catalogue clarifies what role each library type plays in the <strong>subdomain</strong>, how they collaborate, and which dependency limits keep the graph healthy. This is not a file-type taxonomy but a <strong>responsibility</strong> one: who orchestrates the experience, who concentrates domain knowledge, who renders the interface, and what are pure utilities. Each section includes a <strong>TL;DR</strong> to refresh quickly.</p><h3>1) feature · Orchestrating the experience</h3><p><strong>TL;DR:</strong></p><ul><li>Encapsulates a user experience (screen or flow).</li><li>Orchestrates views, navigation, and states (loading/success/error).</li><li><strong>Delegates</strong>: rules and data access → to data-access.</li><li>Doesn’t do HTTP or business logic.</li></ul><p>If this is your first time with the term, skip the summary and read the full section.</p><p><strong>What it is.</strong> A “feature” is <strong>a full screen or flow</strong> bundled with what’s needed for that experience to happen. It decides what to show, when to load, what to do on button click, and where to navigate next. It doesn’t contain business truth nor talk to the server directly: it <strong>orchestrates</strong>; when it needs data or rules, it asks the <strong>public contract</strong> of data-access. Routing, composing views, and transitioning between states (loading/success/error) live here.</p><p><strong>Example.</strong> In an e-commerce, the <em>Checkout</em> feature loads the cart, asks pricing for total with discounts, shows payment errors, and navigates to “order confirmed” at the end. It doesn’t calculate discounts or call the backend: it delegates to domain services exposed by data-access.</p><p><strong>When to create a </strong>feature lib: When there is an <strong>identifiable route or flow</strong> a user can traverse end to end (list, detail, checkout, profile). They are typically lazy-loaded to isolate costs and dependencies.</p><p><strong>Does:</strong> smart containers (facades with a small API to the UI), guards and resolvers tied to navigation, coordination of UI events with domain use cases (via data-access).</p><p><strong>Doesn’t do:</strong> direct HTTP or business rules beyond presentation and orchestration.</p><h3>2) data-access (aka domain) · Knowledge and data access</h3><p><strong>TL;DR:</strong></p><ul><li>Models entities, invariants, and subdomain rules.</li><li>Exposes a stable contract (types/use cases) and <strong>hides</strong> DTOs/transport.</li><li>Encapsulates repositories/effects and cross-domain state.</li><li>Knows nothing about UI or navigation.</li></ul><p><strong>What it is.</strong> If feature is the director, data-access is the <strong>screenwriter and translator</strong>. It defines what each entity means, what rules <strong>cannot be broken</strong> (invariants), and how to talk to the outside world (HTTP/GraphQL/WebSocket/storage). It also maintains <strong>cross-cutting domain state</strong>: shared collections, small read caches, lightweight session that doesn’t belong to a single screen. Goal: keep <strong>business knowledge</strong> stable, testable, and <strong>decoupled from presentation</strong>.</p><p><strong>Example.</strong> Task app: in tasks/data-access you define the Task model (id, title, done) and use cases like loadTasks(), addTask(title), toggleDone(id). If the API returns {task_id, name, completed}, you transform it to Task here. A TasksRepository makes HTTP calls and keeps the last list in memory so multiple features (list and detail) can reuse it without revalidating. UI/features only see methods and types; they don’t see endpoints or headers.</p><p><strong>When to create/extract </strong>data-access lib: When several features share <strong>rules</strong> or <strong>collections</strong>; when <strong>I/O</strong> appears and should be <strong>isolated</strong>; when <strong>business types</strong> emerge (e.g., OrderStatus, Money, TaxBreakdown) that shouldn’t live in the UI; or when the flow requires <strong>verifiable invariants</strong> (e.g., a paid order can’t return to draft). Better to extract <strong>late with evidence</strong> than early “just in case”.</p><p><strong>How it’s exposed.</strong> data-access publishes a stable contract: <strong>types</strong>, <strong>interfaces</strong>, and <strong>use cases</strong> (services/functions). That contract <strong>doesn’t leak</strong> transport (DTOs) or storage; it offers what the rest needs <strong>in the domain’s language</strong>. Thus feature only sees calculatePrice, OrdersRepository.create(orderDraft), or a ProductsQuery—not endpoints or headers.</p><p><strong>What it doesn’t do.</strong> It doesn’t render or decide layouts; it doesn’t contain navigation; it doesn’t “paint” loading/success/error beyond modeling them in its API (e.g., Resource&lt;T&gt;). Visual coordination is feature’s job.</p><p><strong>Common smells.</strong> Exporting raw DTOs as models; duplicating types/validations in ui for not publishing them from data-access; coupling to the router; mixing domain effects into components. Move rules and mappers back to data-access and leave orchestration to feature.</p><h3>3) ui · Pure presentation</h3><p><strong>TL;DR:</strong></p><ul><li>Presentational components with @Input()/@Output().</li><li>No services, no HTTP, no business rules.</li><li>Reusable and easy to test; can be typed using data-access types.</li><li>Focus on render, accessibility, and visual contract; orchestration lives in feature.</li></ul><p><strong>What it is.</strong> If feature sets the play and data-access writes the script, ui are the <strong>actors on stage</strong>. Presentational components that <strong>receive ready-to-render data</strong> and <strong>emit events</strong> when interacting. They don’t navigate, fetch data, or know business rules: they <strong>render</strong> and <strong>delegate</strong>. That deliberate ignorance makes them truly reusable and easy to test.</p><p><strong>Example.</strong> OrderTableComponent receives via @Input() a list of OrderView already mapped and, via @Output(), emits view, edit, or deleteRequested. It doesn’t decide whether a “paid” order can be edited: it just shows a disabled button if told. The decision lives outside, in feature/data-access.</p><p><strong>When to create a </strong>ui lib: When a visual piece can be used in more than one screen or you want to encapsulate an <strong>interface pattern</strong> (table, selector, form, card) with a clear API. Within a subdomain you can have ui that’s specific (e.g., order status badges) and, if the piece is truly cross-cutting, move it to shared/ui.</p><p><strong>Does:</strong> renders with @Input() and emits with @Output(); keeps minimal local state (expanded/collapsed, selection, focus) unrelated to business rules; applies styles, accessibility, and design-system contracts.</p><p><strong>Doesn’t do:</strong> inject domain services, stores, or router; call HTTP; build/transform complex DTOs (expects ready data from data-access).</p><p><strong>Health signals:</strong> small, expressive API (orders, canEdit; editRequested(orderId)); tests with synthetic data and no network/router mocks; design changes without touching feature/data-access. In Angular, ChangeDetectionStrategy.OnPush + immutable inputs favour performance.</p><p><strong>Smells:</strong> the component starts injecting services/selecting store/navigating → it’s a <strong>container</strong> and should live in feature. Outputs with backend jargon (upsert, dtoChanged) → use product language (saveRequested, filtersChanged).</p><h3>4) utils · Pure, generic functions</h3><p><strong>TL;DR:</strong></p><ul><li>Pure, deterministic, stateless functions.</li><li>No business, no I/O, no domain dependencies.</li><li>Use them locally to the subdomain; promote to shared/ only with <strong>real reuse</strong>.</li><li>If it touches business rules, move it to data-access.</li></ul><p><strong>What it is.</strong> The land of <strong>small, deterministic, stateless</strong> functions. With the same input, they return the same output without touching the external world. They reduce day-to-day friction: formatting, parsing, sorting, transforming. When a utility <strong>starts to “know” business</strong>, it stops being utils and should move to data-access.</p><p><strong>Example.</strong> formatCurrency(amount: number, currency: string, locale: string), parseIsoDate(s: string), clamp(n, min, max), partition&lt;T&gt;(arr: T[], fn: (x: T) =&gt; boolean). If you need to compute “final price with VAT and country discount,” that belongs in pricing/data-access.</p><p><strong>When to create/extract </strong>utils: When you spot the <strong>same transformation</strong> repeated across libs; when you can describe the function without naming business concepts; when adding it <strong>clarifies</strong> the code that uses it. If it’s only used by one subdomain and mentions its types, place it under libs/&lt;domain&gt;/&lt;subdomain&gt;/utils. Promote it to shared/utils-* only with real <strong>cross-subdomain</strong> reuse.</p><p><strong>What it doesn’t do.</strong> No caches, no reading env or window, no I/O, no dependency on services or data-access, no coded business policy behind a generic name.</p><p><strong>Health signals:</strong> small, explicit signatures; no side effects; tests without complex mocks; names that reveal intent (toTitleCase, groupByKey). If testing needs stores, router, or global locales, it likely <strong>isn’t</strong> a pure utility.</p><p><strong>Smells:</strong> “utilities” that accept/return backend DTOs; helpers mixing formatting and rules; functions with flags that change semantics → smells like a <strong>domain use case</strong>.</p><h3>5) actions (optional) · Shared event lexicon</h3><p><strong>TL;DR:</strong></p><ul><li>Shared event lexicon for the subdomain (names + payloads).</li><li>Useful when several features publish/consume the <strong>same</strong> events.</li><li>Part of the domain contract; use ubiquitous language.</li><li>Don’t extract if the action is local or your flow isn’t action-driven.</li></ul><p><strong>What it is.</strong> An <strong>action</strong> is a message with a name and payload describing something that happened or we request to happen (OrderPlaced, PaymentFailed). By itself it <strong>does nothing</strong>; it’s for system parts to understand each other: “when this message arrives, trigger this effect, update that state…”. In NgRx, messaging is the axis of the flow: actions → effects/reducers → new state.</p><p><strong>Why an </strong>actions library? When <strong>several </strong>features in the same subdomain publish or react to the <strong>same events</strong>, centralize names and payload shapes to avoid divergence and duplication. Keep names in <strong>ubiquitous language</strong>, avoid leaking UI/transport details, and treat it as <strong>part of the contract</strong> of the subdomain.</p><p><strong>When not to.</strong> If an action only exists for a specific screen, keep it in its feature—don’t export it. If your state isn’t strictly action-driven (Signal Store, lightweight reactive services), you might not need a dedicated lib: keep events near the domain (data-access) or the feature and extract to actions only with <strong>real reuse</strong>.</p><h3>Where do store and effects go?</h3><p>Quick rule: <strong>state</strong> where it’s used; <strong>effects</strong> where domain logic lives.</p><ul><li><strong>View state</strong> (selectors/flags of a specific screen) → feature.</li><li><strong>Domain state/transactions</strong> (collections, permissions, sessions, caches) → data-access.</li><li><strong>Shared actions</strong> when multiple features orchestrate them → actions (optional).</li><li><strong>UI</strong> never knows about the store: wrap it with a container in feature.</li></ul><p>This applies equally to NgRx and <strong>Signal Store</strong>: the separation is still view ↔︎ domain. If an effect talks HTTP or domain repositories, its natural place is data-access.</p><h3>Dependency rules (mini-matrix)</h3><ul><li>feature → may depend on ui, data-access, and utils.</li><li>ui → may depend on types from data-access and on utils.</li><li>data-access → may depend on utils.</li><li>utils → depends on no one.</li></ul><p>Dependencies flow <strong>from orchestration toward details</strong>. feature composes the experience and thus consumes ui to render and data-access for use cases, leaning on utils as needed. The arrow <strong>doesn’t go back</strong>: if ui or data-access depended on feature, we’d mix presentation with business rules and lose freedom to evolve.</p><p>ui stays unaware of the rest: it receives data, emits events, and doesn’t inject services or coordinate effects. That purity makes it reusable and easy to test; when it needs types, it takes them from the contract published by data-access, never from feature.</p><p>data-access concentrates models, invariants, mappers, and repositories and, when applicable, cross-cutting state. To stay stable and testable it knows nothing about navigation or views; it only uses pure utilities. utils depends on no one, avoiding cycles and favouring reuse.</p><p>Respecting these directions yields a predictable graph: the UI can change without touching business logic, the domain can evolve without breaking screens, and utilities serve both without coupling them.</p><h3>Brief reminder on public contract</h3><p>In Nx, a <strong>subdomain</strong> usually consists of several libraries (data-access, feature, ui, utils), and <strong>each library</strong> exposes its own contract from its index.ts. Always consume via those entry points (project aliases) and avoid internal paths. If you cross subdomains, do it only through what each lib publishes. Aliases and <em>boundaries</em> rules were covered in Part 1.</p><h3>Folder example</h3><p>Illustrative structure for subdomain <strong>orders</strong> within domain <strong>sales-app</strong> (adjust names to your business language, but preserve boundaries and contracts):</p><pre>libs/<br>  sales-app/<br>    orders/<br>      data-access/<br>        src/<br>          entities/<br>          dtos/<br>          mappers/<br>          services/<br>          orders.http-client.ts<br>          index.ts<br>      ui/<br>        src/<br>          order-table/<br>          order-badge/<br>          index.ts<br>      feature/<br>        src/<br>          containers/<br>          orders.routes.ts<br>          index.ts<br>      utils/<br>        src/<br>          format-currency.ts<br>          index.ts</pre><p><strong>Flat catalogue alternative</strong> (if you prefer to see the type in the name):</p><pre>libs/<br>  sales-app/<br>    feature-order/<br>    data-access-order/<br>    ui-order/<br>    utils-order/</pre><p>Whichever scheme you pick, <strong>apply a single, consistent criterion</strong> across the repo.</p><h3>When and how to create a new library?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JmO8nNaBuJ0zsR4OeaplQ.png" /><figcaption>Process for creating new libraries</figcaption></figure><p><strong>Signals to make the library generic.</strong> It doesn’t import business entities or need invariants; it expresses itself as a pure function/parametrizable component/service with <strong>interfaces</strong>; tests don’t mention the domain.</p><p><strong>Signals to keep it in the subdomain.</strong> It requires subdomain types (e.g., Price, OrderStatus); it changes when business rules change (discounts, permissions, validations); “genericity” is achieved via flags or mode: &#39;orders&#39; | &#39;bookings&#39; (smells like <strong>over-generalization</strong>).</p><p><strong>Anti-patterns to avoid.</strong> shared/* that <strong>imports subdomain models</strong>; duplicating logic across domains instead of <strong>extracting the generic part</strong> + <strong>injecting a strategy</strong>; a “generic library” that exports <strong>business constants</strong> or <strong>enums</strong>.</p><p><strong>Names and locations (examples).</strong> Truly cross-cutting generic → libs/shared/utils-date, libs/shared/ui/table. Shared across subdomains of the same domain → libs/sales-app/shared/format-price, libs/sales-app/shared/schedule-rules. Subdomain-specific → libs/sales-app/orders/data-access, libs/sales-app/pricing/utils.</p><h3>Conclusion</h3><p>If Part 1 was themap, here we defined the operational pieces and the direction of their dependencies. Working by <strong>subdomains</strong> and library types gives you bounded changes, stable contracts, and freedom to refactor without drama: the UI can evolve without touching business rules, the domain without breaking screens, and utilities continue to serve both. The result is a repository that <strong>expresses the business</strong> when you open libs/, where every change has a natural home.</p><h3>Glossary</h3><p><strong>Subdomain.</strong> A slice within a domain where concepts, flows, or ownership change. Often materializes as several related libs in Nx.</p><p><strong>Library (Nx).</strong> A code unit with index.ts as entry point and clear dependency boundaries. In this article we use feature, data-access, ui, and utils (and actions as optional).</p><p><strong>Feature.</strong> Orchestrates a concrete experience: composes views, routes, and connects the UI with domain use cases.</p><p><strong>Data-access / Domain.</strong> Encapsulates models, invariants, mappers, and repositories; may keep cross-cutting state of the subdomain.</p><p><strong>UI (presentational).</strong> Renders data and emits events without knowing router, stores, or business policies.</p><p><strong>Utils.</strong> Pure, stateless functions; if they depend on business, they belong to the domain, not utils.</p><p><strong>Public contract.</strong> Stable set of exports accessible through each library’s index.ts. Avoid internal paths.</p><p><strong>View state.</strong> Screen-specific flags and selectors; lives in feature.</p><p><strong>Domain state.</strong> Cross-cutting collections/rules (session, permissions, caches); lives in data-access.</p><p><strong>DTO vs domain model.</strong> DTO reflects transport; the model expresses intent and rules. A mapper separates them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98fac2fdb64c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serie: Estructurar librerías en Nx + Angular — Parte 2 · Tipos de librería dentro de un subdominio]]></title>
            <link>https://medium.com/@nijotigajo/serie-estructurar-librer%C3%ADas-en-nx-angular-parte-2-tipos-de-librer%C3%ADa-dentro-de-un-subdominio-057256851221?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/057256851221</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nx]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 13:20:55 GMT</pubDate>
            <atom:updated>2025-11-12T13:21:21.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pU4Q1PAbKT_-R6hR" /><figcaption>Photo by <a href="https://unsplash.com/@tothnorex?utm_source=medium&amp;utm_medium=referral">Norbert Tóth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Esta entrega continúa directamente la Parte 1. Allí fijamos el terreno común: lenguaje ubicuo, dominios y <strong>subdominios</strong>, y acordamos que la estructura del repositorio debe contar la historia del negocio a simple vista. Si aquella fue el mapa, aquí bajamos al terreno: cómo se materializa ese mapa dentro de libs/ y qué límites mantienen todo coherente cuando el proyecto crece. Aunque el foco es Nx + Angular, el 99% es transferible a otros stacks.</p><p>Trabajaremos con un catálogo breve pero suficiente de tipos de librería por <strong>subdominio</strong>: feature, data-access (o domain), ui y utils, con actions como opcional cuando el estado se modela por eventos. Veremos la responsabilidad de cada tipo, cómo colaboran y qué dependencias mantener para que el grafo siga legible. También ubicaremos el estado: qué pertenece a la vista (feature) y qué es transversal al dominio (data-access).</p><p>Cerramos con criterios prácticos para decidir <strong>cuándo crear una librería</strong> y <strong>cuándo extraer </strong>shared: favorece lo genérico solo cuando aporta valor en más de un lugar, sin forzarlo ni sacrificar claridad. La idea es que, cuando cambie la regla de descuentos por ejemplo, sepas exactamente a qué puerta llamar y que el cambio quede encapsulado por significado.</p><blockquote>Las partes más largas tendrán un <strong>TL;DR</strong> para los que ya saben o quieren un resumen.</blockquote><h3>Catálogo de tipos de librería y su papel</h3><p>Este catálogo aclara qué función cumple cada tipo de librería en el <strong>subdominio</strong>, cómo colaboran y qué límites de dependencia mantienen el grafo de dependencias sano. No es una clasificación por archivos, sino por <strong>responsabilidades</strong>: quién orquesta la experiencia, quién concentra el conocimiento del dominio, quién pinta la interfaz y cuáles son utilidades puras.</p><h3>1) feature · Orquestación de la experiencia</h3><p><strong>TL;DR:</strong></p><ul><li>Encapsula una experiencia de usuario (pantalla o flujo).</li><li>Orquesta vistas, navegación y estados (loading/success/error).</li></ul><blockquote><strong>Delegación</strong>: reglas y acceso a datos → data-access.</blockquote><blockquote>No hace HTTP ni implementa lógica de negocio.</blockquote><p>Si es tu primera vez con el término, salta este resumen y lee la sección completa.</p><p><strong>Qué es.</strong> “Feature” es <strong>una pantalla o un flujo completo</strong> empaquetado con lo necesario para que esa experiencia ocurra. Decide qué se muestra, cuándo se carga, qué hacer al pulsar un botón y a qué pantalla se navega después. No contiene la verdad del negocio ni habla con el servidor directamente: <strong>orquesta</strong>; cuando necesita datos o reglas, los pide al <strong>contrato público</strong> de data-access. Aquí viven el <em>routing</em>, la composición de vistas y la transición entre estados (loading/success/error).</p><p><strong>Ejemplo.</strong> En un e‑commerce, la feature <em>Checkout</em> carga el carrito, pide a pricing el total con descuentos, muestra errores de pago y navega a “pedido confirmado” al finalizar. No calcula descuentos ni llama al backend: delega en servicios del dominio expuestos por data-access.</p><p><strong>Cuándo crear una lib </strong>feature : Cuando exista una <strong>ruta o flujo identificable</strong> que el usuario pueda recorrer de principio a fin (listado, detalle, checkout, perfil). Suelen cargarse en <em>lazy</em> para aislar costes y dependencias.</p><p><strong>Hace:</strong> contenedores inteligentes (fachadas con API simple a la UI), <em>guards</em> y <em>resolvers</em> ligados a la navegación, y coordinación de eventos de UI con casos de uso del dominio (vía data-access).</p><p><strong>No hace:</strong> HTTP directo ni reglas de negocio más allá de presentación y orquestación.</p><h3>2) data-access (también domain) · Conocimiento y acceso a datos</h3><p><strong>TL;DR:</strong></p><ul><li>Modela entidades, invariantes y reglas del subdominio.</li><li>Expone contrato estable (tipos/casos de uso) y <strong>oculta</strong> DTOs/transporte.</li><li>Encapsula repositorios/efectos y estado transversal del dominio.</li><li>No conoce UI ni navegación.</li></ul><p><strong>Qué es.</strong> Si feature es el director, data-access es el <strong>guionista y traductor</strong>. Define qué significa cada entidad, qué reglas <strong>no se pueden romper</strong> (invariantes) y cómo se habla con el exterior (HTTP/GraphQL/WebSocket/almacenamiento). También mantiene <strong>estado transversal del dominio</strong>: colecciones compartidas, pequeñas cachés de lectura, sesión ligera que no pertenece a una sola pantalla. El objetivo: que el <strong>conocimiento del negocio</strong> sea estable, testeable y <strong>ajeno a la presentación</strong>.</p><p><strong>Ejemplo.</strong> App de tareas: en tasks/data-access defines el modelo Task (id, title, done) y casos de uso como loadTasks(), addTask(title) y toggleDone(id). Si la API devuelve {task_id, name, completed}, aquí lo transformas a Task. Un TasksRepository hace las llamadas HTTP y guarda en memoria la última lista para que varias features (lista y detalle) la reutilicen sin revalidar. La UI y las features solo ven métodos y tipos; no ven endpoints ni headers.</p><p><strong>Cuándo crear/extraer </strong>data-access: Cuando varias features comparten <strong>reglas</strong> o <strong>colecciones</strong>; cuando aparece <strong>I/O</strong> que conviene <strong>aislar</strong>; cuando emergen <strong>tipos de negocio</strong> (p. ej., OrderStatus, Money, TaxBreakdown) que no deben vivir en la UI; o cuando el flujo requiere <strong>invariantes</strong> verificables (p. ej., un pedido pagado no puede volver a borrador). Mejor extraer <strong>tarde con evidencia</strong> que pronto “por si acaso”.</p><p><strong>Cómo se expone.</strong> data-access publica un contrato estable: <strong>tipos</strong>, <strong>interfaces</strong> y <strong>casos de uso</strong> (servicios/funciones). Ese contrato <strong>no filtra</strong> transporte (DTOs) ni almacenamiento; ofrece lo que el resto necesita <strong>en el idioma del dominio</strong>. Así, feature solo ve calculatePrice, OrdersRepository.create(orderDraft) o un ProductsQuery, no endpoints ni headers.</p><p><strong>Qué no hace.</strong> No renderiza ni decide <em>layouts</em>; no contiene navegación; no “pinta” estados de carga/éxito/error más allá de modelarlos en su API (por ejemplo, Resource&lt;T&gt;). La coordinación visual la hace la feature.</p><p><strong>Olores típicos.</strong> Exportar DTOs crudos como modelos; duplicar tipos/validaciones en ui por no publicarlos desde data-access; acoplarse al <em>router</em>; mezclar efectos de dominio en componentes. Devuelve reglas y mapeadores a data-access y deja a feature la orquestación.</p><h3>3) ui · Presentación pura</h3><p><strong>TL;DR:</strong></p><ul><li>Componentes presentacionales (dumb) con @Input()/@Output().</li><li>Sin servicios, sin HTTP ni reglas de negocio.</li><li>Reutilizables y fáciles de testear; pueden tiparse con tipos de data-access.</li><li>Se enfocan en <em>render</em>, accesibilidad y contrato visual; la orquestación vive en feature.</li></ul><p><strong>Qué es.</strong> Si feature decide la obra y data-access escribe el guion, ui son los <strong>actores en escena</strong>. Componentes presentacionales que <strong>reciben datos listos</strong> y <strong>emiten eventos</strong> al interactuar. No navegan, no piden datos, no conocen reglas del negocio: <strong>muestran</strong> y <strong>delegan</strong>. Esa ignorancia deliberada los hace verdaderamente reutilizables y fáciles de probar.</p><p><strong>Ejemplo.</strong> OrderTableComponent recibe por @Input() una lista de OrderView ya mapeada y, por @Output(), emite view, edit o deleteRequested. No decide si un pedido “pagado” puede editarse: solo muestra un botón deshabilitado si así se le indica. La decisión vive fuera, en feature/data-access.</p><p><strong>Cuándo crear una lib </strong>ui: Cuando una pieza visual pueda usarse en más de una pantalla o quieras encapsular un <strong>patrón de interfaz</strong> (tabla, selector, formulario, <em>card</em>) con API clara. Dentro de un subdominio puedes tener ui específica (p. ej., <em>badges</em> de estado de pedidos) y, si la pieza es realmente transversal, moverla a shared/ui.</p><p><strong>Hace:</strong> renderiza con @Input() y emite con @Output(); mantiene estados locales mínimos (expandido/colapsado, selección, foco) ajenos a reglas del negocio; aplica estilos, accesibilidad y contratos del <em>design system</em>.</p><p><strong>No hace:</strong> inyectar servicios de dominio, <em>stores</em> o <em>router</em>; llamar HTTP; construir/transformar DTOs complejos (espera datos listos desde data-access).</p><p><strong>Señales de salud:</strong> API pequeña y expresiva (orders, canEdit; editRequested(orderId)); tests con datos sintéticos sin <em>mocks</em> de red/routeo; cambios de diseño sin tocar feature/data-access. En Angular, ChangeDetectionStrategy.OnPush + <em>inputs</em> inmutables favorecen rendimiento.</p><p><strong>Olores:</strong> el componente empieza a inyectar servicios/seleccionar <em>store</em>/navegar → es un <strong>contenedor</strong> y debería vivir en feature. <em>Outputs</em> con jerga de backend (upsert, dtoChanged) → usa lenguaje de producto (saveRequested, filtersChanged).</p><h3>4) utils · Funciones puras y genéricas</h3><p><strong>TL;DR:</strong></p><ul><li>Funciones puras, deterministas y sin estado.</li><li>Sin negocio, sin I/O ni dependencias de dominio.</li><li>Úsalas locales al subdominio; promuévelas a shared/ solo con <strong>reuso real</strong>.</li><li>Si toca reglas del negocio, muévelo a data-access.</li></ul><p><strong>Qué es.</strong> Terreno de funciones <strong>pequeñas, deterministas y sin estado</strong>. Con el mismo <em>input</em>, dan el mismo <em>output</em> sin tocar el mundo exterior. Reducen fricción cotidiana: formatear, <em>parsear</em>, ordenar, transformar. Cuando una utilidad <strong>empieza a “saber” de negocio</strong>, deja de ser utils y debe moverse a data-access.</p><p><strong>Ejemplo.</strong> formatCurrency(amount: number, currency: string, locale: string), parseIsoDate(s: string), clamp(n, min, max), partition&lt;T&gt;(arr: T[], fn: (x: T) =&gt; boolean). Si necesitas calcular “precio final con IVA y descuento por país”, eso pertenece a pricing/data-access.</p><p><strong>Cuándo crear/extraer </strong>utils: Cuando detectes la <strong>misma transformación</strong> repetida en varias libs; cuando puedas describir la función sin nombrar conceptos del negocio; cuando añadirla <strong>aclare</strong> el código que la usa. Si solo la usa un subdominio y menciona sus tipos, colócala como libs/&lt;dominio&gt;/&lt;subdominio&gt;/utils. Promuévela a shared/utils-* solo con reuso real <strong>entre subdominios</strong>.</p><p><strong>Qué no hace.</strong> No mantiene cachés, no lee del entorno ni del window, no hace I/O, no depende de servicios ni de data-access, no codifica políticas de negocio tras un nombre genérico.</p><p><strong>Señales de salud:</strong> firmas pequeñas y explícitas; ausencia de efectos secundarios; tests sin <em>mocks</em> complejos; nombres que revelan intención (toTitleCase, groupByKey). Si para testear necesitas <em>stores</em>, <em>router</em> o <em>locales</em> globales, probablemente <strong>no</strong> es una utilidad pura.</p><p><strong>Olores:</strong> “utilidades” que aceptan o devuelven DTOs de backend; <em>helpers</em> que mezclan formato y reglas; funciones con <em>flags</em> que cambian semántica → eso huele a <strong>caso de uso de dominio</strong>.</p><h3>5) actions (opcional) · Léxico de eventos compartido</h3><p><strong>TL;DR:</strong></p><ul><li>Léxico compartido de eventos del subdominio (nombres + <em>payloads</em>).</li><li>Útil cuando varias feature publican/consumen los <strong>mismos</strong> eventos.</li><li>Parte del contrato del dominio; usa lenguaje ubicuo.</li><li>No extraigas si la acción es local o tu flujo no es <em>action‑driven</em>.</li></ul><p><strong>Qué es.</strong> Una <strong>acción</strong> es un mensaje con un nombre y un <em>payload</em> que describe algo que ocurrió o que solicitamos que ocurra (OrderPlaced, PaymentFailed). Por sí sola <strong>no hace nada</strong>; sirve para que las piezas del sistema se entiendan: “cuando llegue este mensaje, dispara tal efecto, actualiza tal estado…”. En NgRx, la mensajería es el eje del flujo: acciones → efectos/<em>reducers</em> → nuevo estado.</p><p><strong>¿Por qué una librería de </strong>actions? Cuando <strong>varias </strong>feature del mismo subdominio publican o reaccionan a los <strong>mismos eventos</strong>, conviene centralizar nombres y forma de <em>payloads</em> para evitar divergencias y duplicidades. Mantén nombres en <strong>lenguaje ubicuo</strong>, evita que filtren detalles de UI/transporte y trátala como <strong>parte del contrato</strong> del subdominio.</p><p><strong>Cuándo no.</strong> Si una acción solo existe para una pantalla concreta, déjala en su feature y no la exportes. Si tu estado no es estrictamente <em>action‑driven</em> (Signal Store, servicios reactivos ligeros), quizá no necesitas una lib específica: conserva los eventos cerca del dominio (data-access) o de la feature y extrae a actions solo con <strong>reuso real</strong>.</p><h3>¿Dónde van store y efectos?</h3><p>Regla rápida: <strong>estado</strong> donde se usa; <strong>efectos</strong> donde reside la lógica del dominio.</p><ul><li><strong>Estado de vista</strong> (selectores/flags propios de una pantalla) → feature.</li><li><strong>Estado/transacciones del dominio</strong> (colecciones, permisos, sesiones, cachés) → data-access.</li><li><strong>Acciones compartidas</strong> cuando varias feature las orquestan → actions (opcional).</li><li><strong>UI</strong> nunca conoce el <em>store</em>: envuélvela con un contenedor en feature.</li></ul><p>Esto aplica igual a NgRx y a <strong>Signal Store</strong>: la separación sigue siendo vista ↔︎ dominio. Si un <em>effect</em> habla con HTTP o repositorios de dominio, su lugar natural es data-access.</p><h3>Reglas de dependencia (mini‑matriz)</h3><ul><li>feature → puede depender de ui, data-access y utils.</li><li>ui → puede depender de tipos de data-access y de utils.</li><li>data-access → puede depender de utils.</li><li>utils → no depende de nadie.</li></ul><p>Las dependencias fluyen <strong>de la orquestación hacia los detalles</strong>. feature compone la experiencia y, por ello, consume ui para renderizar y data-access para casos de uso, apoyándose puntualmente en utils. La flecha <strong>no vuelve</strong>: si ui o data-access dependieran de feature, mezclaríamos presentación con reglas de negocio y perderíamos libertad de evolución.</p><p>ui se mantiene ajena al resto: recibe datos, emite eventos y no inyecta servicios ni coordina efectos. Esa pureza la hace reutilizable y fácil de probar; cuando necesita tipos, los toma del contrato publicado por data-access, nunca de feature.</p><p>data-access concentra modelos, invariantes, mapeadores y repositorios y, cuando aplica, estado transversal. Para ser estable y testeable no conoce navegación ni vistas; solo recurre a utilidades puras. utils no depende de nadie, lo que evita bucles y favorece la reutilización.</p><p>Respetar estas direcciones produce un grafo predecible: la UI puede cambiar sin tocar el negocio, el dominio puede evolucionar sin romper pantallas y las utilidades sirven a ambos sin acoplarlos.</p><h3>Recordatorio breve sobre contrato público</h3><p>En Nx, un <strong>subdominio</strong> suele componerse de varias librerías (data-access, feature, ui, utils) y <strong>cada librería</strong> expone su propio contrato desde su index.ts. Consume siempre a través de esos <em>entry points</em> (alias del proyecto) y evita rutas internas. Si cruzas subdominios, hazlo solo mediante lo que cada lib publica. La configuración de <em>aliases</em> y las reglas de <em>boundaries</em> ya se trataron en la Parte 1.</p><h3>Ejemplo de carpetas</h3><p>Estructura ilustrativa para el subdominio <strong>orders</strong> dentro del dominio <strong>app-ventas</strong> (ajusta nombres a tu lenguaje de negocio, pero preserva límites y contratos):</p><pre>libs/<br>  app-ventas/<br>    orders/<br>      data-access/<br>        src/<br>          entities/<br>          dtos/<br>          mappers/<br>          services/<br>          orders.http-client.ts<br>          index.ts<br>      ui/<br>        src/<br>          order-table/<br>          order-badge/<br>          index.ts<br>      feature/<br>        src/<br>          containers/<br>          orders.routes.ts<br>          index.ts<br>      utils/<br>        src/<br>          format-currency.ts<br>          index.ts</pre><p><strong>Alternativa de catálogo plano</strong> (si prefieres ver el tipo en el nombre):</p><pre>libs/<br>  app-ventas/<br>    feature-order/<br>    data-access-order/<br>    ui-order/<br>    utils-order/</pre><p>Sea cual sea el esquema, <strong>mantén un criterio único</strong> en todo el repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5mXFUrnGOJODk9zxjDbzA.png" /><figcaption>Flujo de proceso de crear librerías</figcaption></figure><p><strong>Señales para convertir la librería en genérica.</strong> No importa entidades del negocio ni necesita invariantes; se expresa como función pura/componente parametrizable/servicio con <strong>interfaces;</strong> tests sin mencionar el dominio.</p><p><strong>Señales para mantener en el subdominio.</strong> Requiere tipos del subdominio (p. ej., Price, OrderStatus); cambia cuando cambian reglas de negocio (descuentos, permisos, validaciones); la “genericidad” se logra a base de <em>flags</em> o mode: &#39;orders&#39; | &#39;reservas&#39; (huele a <strong>sobregeneralización</strong>).</p><p><strong>Antipatrones a evitar.</strong> shared/* que <strong>importa modelos de subdominio</strong>; duplicar lógica en varios dominios en lugar de <strong>extraer la parte genérica</strong> + <strong>inyectar estrategia</strong>; una “librería genérica” que exporta <strong>constantes</strong> o <strong>enums</strong> de negocio.</p><p><strong>Nombres y ubicaciones (ejemplos).</strong> Genérica transversal → libs/shared/utils-date, libs/shared/ui/table. Compartida entre subdominios del mismo dominio → libs/app-ventas/shared/format-price, libs/app-ventas/shared/schedule-rules. Específica de subdominio → libs/app-ventas/orders/data-access, libs/app-ventas/pricing/utils.</p><h3>Conclusión</h3><p>Si en la Parte 1 trazamos el mapa, aquí definimos las piezas operativas y el sentido de sus dependencias. Trabajar por <strong>subdominios</strong> y tipos de librería te da cambios acotados, contratos estables y libertad para refactorizar sin sobresaltos: la UI puede evolucionar sin tocar reglas de negocio, el dominio sin romper pantallas y las utilidades seguir sirviendo a ambos. El resultado es un repositorio que <strong>expresa el negocio</strong> al abrir libs/ y en el que cada cambio tiene un lugar natural.</p><h3>Glosario</h3><p><strong>Subdominio.</strong> Recorte dentro de un dominio donde cambian conceptos, flujos o responsables. Suele materializarse como varias librerías relacionadas en Nx.</p><p><strong>Librería (Nx).</strong> Unidad de código con index.ts como punto de entrada y límites de dependencia claros. En este artículo usamos feature, data-access, ui y utils (y actions como opcional).</p><p><strong>Feature.</strong> Orquesta una experiencia concreta: compone vistas, enruta y conecta la UI con casos de uso del dominio.</p><p><strong>Data-access / Domain.</strong> Encapsula modelos, invariantes, mapeadores y repositorios; puede mantener estado transversal del subdominio.</p><p><strong>UI (presentacional).</strong> Renderiza datos y emite eventos sin conocer <em>router</em>, <em>stores</em> ni políticas de negocio.</p><p><strong>Utils.</strong> Funciones puras y sin estado; si dependen del negocio, pertenecen al dominio, no a utils.</p><p><strong>Contrato público.</strong> Conjunto estable de exportaciones accesibles a través del index.ts de cada librería. Evita rutas internas.</p><p><strong>Estado de vista.</strong> <em>Flags</em> y <em>selectores</em> propios de una pantalla; reside en feature.</p><p><strong>Estado de dominio.</strong> Colecciones/reglas transversales (sesión, permisos, cachés); reside en data-access.</p><p><strong>DTO vs. modelo de dominio.</strong> El DTO refleja transporte; el modelo expresa intención y reglas. Un mapeador separa ambos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057256851221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estructurar librerías en Nx — Parte 1: Dominios]]></title>
            <link>https://medium.com/@nijotigajo/estructurar-librer%C3%ADas-en-nx-parte-1-dominios-3a687c314bfc?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a687c314bfc</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 16:24:17 GMT</pubDate>
            <atom:updated>2025-10-28T20:55:49.646Z</atom:updated>
            <content:encoded><![CDATA[<h3>Estructurar librerías en Nx — Parte 1: Dominios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBgQIJvjetna3r4W" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleriacom?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@nijotigajo/structuring-libraries-in-nx-part-1-domains-7c82290886aa">Disponible en inglés</a></p><p>Esta es la primera parte de 2 posts sobre mi camino de aprender no solo a escribir código, sino <strong>dónde</strong> ponerlo y por qué. El problema parece simple, pero la respuesta tiene décadas de discusión detrás. Aquí comparto lo que me ha funcionado en proyectos reales, apoyado en documentación de Angular Architects y Nx.</p><p>Aunque use Angular + Nx en mi día a día, <strong>los conceptos principales de esta parte son independientes del stack</strong>. También hay un glosario al final si necesitas un resumen rápido de la terminología que voy a usar.</p><h3>Lenguaje ubicuo, dominio y subdominio</h3><p>Durante mis primeros años programando, me lanzaba a escribir código sin haber decidido cómo organizarlo. Hoy me diría a mí mismo que antes hay que entender el <strong>lenguaje de negocio</strong> (o lenguaje ubicuo) y usarlo para definir los <strong>dominios</strong> y <strong>subdominios</strong>. Estos terminos provienen del mundo de <a href="https://es.wikipedia.org/wiki/Dise%C3%B1o_guiado_por_el_dominio">Domain-Driven Design</a>.</p><p>El <strong>lenguaje ubicuo</strong> es el vocabulario preciso que negocio y desarrollo comparten para nombrar entidades y acciones. Si se llama “Pedido” en la organización, no debería llamarse “Orden” en el código. Si existe el evento “Reserva confirmada”, ese nombre debe aparecer en historias de usuario, métodos y diagramas. La idea es <strong>evitar sinónimos</strong> y malentendidos.</p><p>Entonces, <strong>¿qué es un dominio?</strong> Es <strong>una parte de la realidad del negocio que estamos modelando.</strong> No es una carpeta ni una capa técnica: es el p<strong>roblema de negocio</strong> que queremos resolver. En el código, ese dominio se <strong>representa mediante una estructura de carpetas y librerías</strong> que reflejan sus partes y responsabilidades, de modo que la organización del repositorio exprese el lenguaje del negocio y no solo la tecnología que lo implementa. No porque el dominio sea el código, sino porque el código debe expresar su significado.</p><p>Un <strong>subdominio</strong> es <strong>un corte natural dentro del dominio</strong>, cuando cambian conceptos, flujos o responsables. Separarlos ayuda a aislar cambios y entender dependencias de un vistazo.</p><p>Ejemplos rápidos:</p><ul><li><strong>E-commerce</strong> / <strong>Ventas</strong> -&gt; Catálogo, Pricing, Pedidos</li><li><strong>Restaurante</strong> / <strong>Reservas</strong> -&gt; Mesas, Turnos, Confirmaciones</li><li><strong>Gimnasio</strong> / <strong>Socios</strong> -&gt; Altas, Cuotas, Accesos</li></ul><blockquote><strong>Nota</strong>: Aquí uso “dominio/subdominio” como herramienta práctica para organizar el código. En DDD formal se diferencia entre dominio/subdominio (problema) y bounded context (solución). Aquí simplifico esa distinción para centrarnos en agrupar el código por significado, no por capas técnicas.</blockquote><h3>De organizar por capas técnicas a organizar por significado</h3><p>Un error habitual es organizar el proyecto por categorías técnicas: <em>components, services, state.</em> Funciona, hasta que cambias una regla de negocio y la lógica está repartida en 4 carpetas sin conexión aparente.</p><p>Organizar por <strong>dominios y subdominios</strong> invierte la lógica: se engloban las piezas técnicas por <strong>significado</strong>.</p><p>En una app de ventas, si mañana cambia el cálculo de descuentos, el PR ocurre en el <strong>subdominio pricing,</strong> no buscando archivos por todo el proyecto. Esto reduce cambios de contexto y dependencias accidentales.</p><h3>Cómo reconocer dominios y subdominios</h3><p>De la teoría a la práctica, ¿cómo se recorta de verdad en un proyecto real? Hay muchas formas, pero estas tres funcionan casi siempre. Cada una ataca el problema desde un ángulo distinto: <strong>responsabilidades</strong>, <strong>significado</strong>, y <strong>estado</strong>.</p><p><strong>1 — Cuando cambian los responsables, cambia el subdominio</strong><br>Si diferentes etapas de un proceso recaen en personas, equipos o roles distintos, ahí suele haber un corte natural. No es solo organización interna: cada rol tiene prioridades, vocabulario y reglas distintas, y eso debe reflejarse en el código.</p><p>Separarlos evita que una entidad termine intentando satisfacer necesidades contradictorias.</p><p>Ejemplo:</p><ul><li>En un e-commerce, quien gestiona el catálogo no es quien calcula precios, ni quien procesa pedidos. Por eso Catálogo, Pricing y Pedidos viven en subdominios distintos dentro de Ventas.</li></ul><p><strong>2 — Si una palabra significa cosas diferentes según el contexto, son subdominios distintos<br></strong> Este punto detecta ambigüedades en el lenguaje ubicuo. Cuando la misma palabra se usa para cosas distintas, lo correcto no es “forzar un modelo universal”, es separar modelos, cada uno con su propio sentido.</p><p>Ejemplo con “Producto”:</p><ul><li>En Catálogo significa nombre, fotos, categorías.</li><li>En Pricing significa tarifas, descuentos, impuestos.</li><li>En Logística significa peso, volumen, métodos de envío.</li></ul><p>Si usas el mismo modelo de Producto para todo, tarde o temprano lo rompes intentando satisfacer todos estos significados. Separar subdominios evita eso.</p><p><strong>3 — Los eventos que cambian el estado marcan fronteras de subdominio</strong><br> Cuando un evento de negocio cambia la responsabilidad o el “dueño” de la siguiente acción, ahí normalmente hay un límite de subdominio.<br> Los eventos son puntos de corte naturales porque representan un cambio en qué está pasando y quién decide.</p><p>Ejemplos rápidos:</p><ul><li>“Pago confirmado” -&gt; deja de importar la intención de compra y empieza la logística de envío.</li><li>“Reserva confirmada” -&gt; se pasa de reservas a gestión de sala.</li><li>“Cuota cobrada” -&gt; se pasa de facturación a acceso.</li></ul><p>Estos eventos son perfectos para definir límites porque nadie discute su existencia en el negocio, ya están ahí, solo los estás usando como guías.</p><p>Si quieres profundizar, puedes explorar <a href="https://en.wikipedia.org/wiki/Event_storming"><strong>Event Storming</strong>:</a> un taller visual en el que se colocan eventos de negocio en una línea temporal para observar cómo se organiza el flujo de trabajo. Esta técnica ayuda a identificar subdominios y límites naturales sin partir de suposiciones, sino a partir del comportamiento real del sistema.</p><h3>Procedimiento práctico</h3><p>1 — Lista los <strong>procesos principales</strong> de la aplicación.</p><p>2 — Marca <strong>roles</strong>, <strong>términos</strong> y <strong>eventos</strong> clave.</p><p>3 — Propón <strong>cortes de dominio/subdominio</strong> que:</p><ul><li><strong>aumenten cohesión</strong> interna</li><li><strong>reduzcan acoplamiento</strong> entre zonas</li></ul><p>4 — <strong>Valídalo</strong> explicándolo al equipo. Si todo el mundo asiente sin fruncir el ceño -&gt; vas bien.</p><h3>De la idea a las carpetas</h3><blockquote><strong>Nota sobre la estructura:</strong> en Nx y los proyectos de código en general, los dominios y subdominios suelen aparecer como <strong>c</strong>arpetas, no como librerías Nx en sí mismas. A partir de aquí, hablaremos principalmente de subdominios, y profundizaremos en las librerías Nx en la Parte 2.</blockquote><p>Una vez que tenemos los dominios y subdominios claros, podemos trasladarlos al código, asegurando que la estructura deba permitir leer el negocio directamente del árbol de archivos, sin abrir código.</p><pre>libs/<br>   app-ventas/<br>     catalog/<br>     pricing/<br>     orders/<br>   shared/</pre><p>Aquí, app-ventas representa el dominio Ventas y cada subcarpeta (catalog, pricing, orders) implementa un subdominio concreto.</p><ul><li>app-ventas/catalog -&gt; todo lo relacionado con <strong>mostrar y gestionar catálogo</strong></li><li>app-ventas/pricing -&gt; <strong>reglas y cálculos de precios</strong></li><li>app-ventas/orders -&gt;<strong> creación y seguimiento de pedidos</strong></li><li>shared/ -&gt; utilidades que <strong>no pertenecen a ningún subdominio</strong> (excepciones, helpers, pipes, etc.)</li></ul><p>La clave aquí es que <strong>cada subdominio contiene sus propias piezas técnicas</strong><br> (componentes UI, servicios, stores, casos de uso, DTOs, etc.), pero organizadas por significado, no por tipo.</p><p>Si mañana cambia la regla de descuentos, el PR ocurre en libs/app-ventas/pricing, no buscando archivos dispersos por<em> services, state </em>y<em> components.</em></p><h3>¿Cómo se comunican los subdominios entre sí?</h3><p>A través de un<strong> contrato público:</strong> tipos, interfaces y servicios que cada subdominio expone desde su archivo <em>index.ts</em>.</p><pre>libs/app-ventas/pricing/index.ts</pre><p>La comunicación entre subdominios solo sucede a través de ese contrato. No hay imports entre carpetas internas. No hay atajos tipo ../../internal/model.ts.</p><p>Si <strong>catalog</strong> necesita saber el precio final de un producto:</p><ul><li>Importa calculatePrice desde el <strong>contrato público de pricing</strong></li><li>No desde sus internals</li></ul><p>En Typescript y Nx esto se refuerza con:</p><ul><li><a href="https://www.typescriptlang.org/tsconfig/#paths">Path aliases</a> (@org/app-ventas/pricing)</li><li>Regla <a href="https://nx.dev/docs/features/enforce-module-boundaries">@nx/enforce-module-boundaries</a></li></ul><p>Esto mantiene <strong>límites claros,</strong> reduce acoplamiento y hace que el código sea más fácil de mantener a largo plazo.</p><h3>En resumen</h3><ul><li>La estructura del proyecto debe <strong>contar la historia</strong> del negocio al leerla.</li><li>Un subdominio no es una carpeta al azar: expresa un <strong>concepto de negocio.</strong></li><li>Cada subdominio es <strong>dueño de su modelo.</strong></li><li>La interacción entre subdominios se hace <strong>explícita</strong> a través de contratos públicos.</li></ul><blockquote>Puedes medir si tu arquitectura va bien así: alguien nuevo en el equipo debería entender el negocio mirando solo el árbol de libs/</blockquote><h3>Próximo paso: Anatomía interna por subdominio</h3><p>Ahora que tenemos <strong>el mapa</strong> (dominios, subdominios y límites), en la Parte 2 completaremos el modelo con librerías de Nx (<em>feature, ui, data, util</em>) dentro de los subdominios, y sus reglas de dependencia. Con esto, ya tenemos una base sólida para que el código refleje el lenguaje del negocio. En la siguiente parte veremos cómo mantener ese orden a medida que el proyecto crece.</p><h3>Glosario</h3><p><strong>Lenguaje ubicuo</strong><br>Vocabulario compartido entre negocio y desarrollo. Los nombres que usamos en conversaciones son los mismos que usamos en el código. Evita sinónimos y ambigüedades.</p><p><strong>Dominio</strong><br>Una parte de la realidad del negocio que queremos modelar (p. ej. Ventas, Reservas, Socios). Es el problema que el software quiere resolver. No es una carpeta ni una capa técnica.</p><p><strong>Subdominio</strong><br>Un corte natural dentro del dominio, donde cambian conceptos, flujos o responsables (p. ej. dentro de Ventas: Catálogo, Pricing, Pedidos). Cada subdominio encapsula su propio modelo y sus reglas.</p><p><strong>Modelo del subdominio</strong><br>El conjunto de entidades, tipos, casos de uso y lógica que solo tienen sentido en ese subdominio. No son “globales”, porque no significan lo mismo en otros contextos.</p><p><strong>Contratos públicos</strong><br>La API estable que un subdominio expone a otros (tipos, interfaces y servicios reexportados desde index.ts en caso de Typescript). Es la única manera en la que los subdominios se comunican entre sí.</p><p><strong>Internals</strong><br>Código privado al subdominio (modelos, mappers, stores internos, adaptadores, validaciones, etc.). Puede cambiar sin aviso. No debe importarse desde otros subdominios.</p><p><strong>Cohesión</strong><br>Lo que está junto porque pertenece junto. Un subdominio con buena cohesión agrupa lógica que trata del mismo concepto.</p><p><strong>Acoplamiento</strong><br>Dependencias innecesarias entre partes del sistema. Queremos alto nivel de cohesión, bajo acoplamiento.</p><h3>Recursos</h3><ul><li><a href="https://www.angulararchitects.io/en/ebooks/micro-frontends-and-moduliths-with-angular/">https://www.angulararchitects.io/en/ebooks/micro-frontends-and-moduliths-with-angular/</a></li><li><a href="https://www.angulararchitects.io/en/ebooks/modern-angular/">https://www.angulararchitects.io/en/ebooks/modern-angular/</a></li><li><a href="https://go.nx.dev/angular-patterns-ebook">https://go.nx.dev/angular-patterns-ebook</a></li><li><a href="https://www.google.es/books/edition/Domain_Driven_Design/hHBf4YxMnWMC?hl=en&amp;gbpv=1&amp;printsec=frontcover">https://www.google.es/books/edition/Domain_Driven_Design/hHBf4YxMnWMC?hl=en&amp;gbpv=1&amp;printsec=frontcover</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a687c314bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring libraries in Nx — Part 1: Domains]]></title>
            <link>https://medium.com/@nijotigajo/structuring-libraries-in-nx-part-1-domains-7c82290886aa?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c82290886aa</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 16:23:38 GMT</pubDate>
            <atom:updated>2025-10-28T20:53:50.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Structuring libraries in Nx — Part 1: Domains</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xqKouSMh6OfxeQ3T" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleriacom?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@nijotigajo/estructurar-librer%C3%ADas-en-nx-parte-1-dominios-3a687c314bfc">Also available in Spanish</a></p><p>This is the first part of 2 posts about my journey of learning not only to write code, but <strong>where</strong> to put it and why. The problem seems simple, but the answer has decades of discussion behind it. Here I share what has worked for me in real projects, supported by documentation from Angular Architects and Nx.</p><p>Even though I use Angular + Nx in my day-to-day, <strong>the main concepts in this part are stack-independent.</strong> There is also a glossary at the end if you need a quick summary of the terminology I’m going to use.</p><h3>Ubiquitous language, domain and subdomain</h3><p>During my first years programming, I jumped into writing code without having decided how to organize it. Today I would tell myself that before anything you have to understand the <strong>business language</strong> (or ubiquitous language) and use it to define <strong>domains</strong> and <strong>subdomains</strong>. These terms come from the world of <a href="https://en.wikipedia.org/wiki/Domain-driven_design">Domain-Driven Design</a>.</p><p>The <strong>ubiquitous language</strong> is the precise vocabulary that business and development share to name entities and actions. If it’s called “Order” in the organization, it shouldn’t be called “Request” in the code. If there is the event “Reservation confirmed”, that name must appear in user stories, methods, and diagrams. The idea is to <strong>avoid synonyms</strong> and misunderstandings.</p><p>So, what’s a <strong>domain</strong>? It is <strong>a part of the business reality that we are modeling</strong>. It is not a folder nor a technical layer: it is the <strong>business problem </strong>we want to solve. In the code, that domain is <strong>represented through a structure of folders and libraries</strong> that reflect its parts and responsibilities, so that the organization of the repository expresses the business language and not only the technology that implements it. Not because the domain is the code, but because the code must express its meaning.</p><p>A <strong>subdomain</strong> is a <strong>natural slice within the domain,</strong> when concepts, flows, or responsible parties change. Separating them helps isolate changes and understand dependencies at a glance.</p><p>Quick examples:</p><ul><li><strong>E-commerce</strong> / <strong>Sales</strong> -&gt; Catalog, Pricing, Orders</li><li><strong>Restaurant</strong> / <strong>Reservations</strong> -&gt; Tables, Shifts, Confirmations</li><li><strong>Gym</strong> / <strong>Membership</strong> -&gt; Sign-ups, Fees, Access</li></ul><blockquote><strong>Note</strong>: Here I use “domain/subdomain” as a practical tool to organize code.<br> In formal DDD there is a distinction between domain/subdomain (problem) and bounded context (solution). Here I simplify that distinction to focus on grouping code by meaning, not by technical layers.</blockquote><h3>From organizing by technical layers to organizing by meaning</h3><p>A common mistake is to organize the project by technical categories: <em>components, services, state.</em> It works, until you change a business rule and the logic is spread across 4 folders with no apparent connection.</p><p>Organizing by <strong>domains and subdomains</strong> reverses the logic: the technical pieces are bound together by <strong>meaning.</strong></p><p>If tomorrow the discount calculation changes, the PR happens in the <strong>subdomain pricing</strong>, not by looking for files throughout the project. This reduces context switching and accidental dependencies.</p><h3>How to recognize domains and subdomains</h3><p>From theory to practice, how do you actually slice a real project into domains and subdomains? There are many ways, but these three almost always work. Each one tackles the problem from a different angle: <strong>responsibilities</strong>, <strong>meaning</strong>, and <strong>state</strong>.</p><p><strong>1 — When the responsible parties change, the subdomain changes</strong><br> If different stages of a process fall to different people, teams, or roles, there is usually a natural cut there. It’s not just internal organization: each role has different priorities, vocabulary, and rules, and that must be reflected in the code.</p><p>Separating them prevents an entity from ending up trying to satisfy contradictory needs.</p><p>Example:</p><ul><li>In an e-commerce, the person who manages the catalog is not the person who calculates prices, nor the person who processes orders.<br> That’s why Catalog, Pricing, and Orders live in different subdomains within Sales.</li></ul><p><strong>2 — If a word means different things depending on the context, they are different subdomains</strong><br>This point detects ambiguities in the ubiquitous language. When the same word is used for different things, the correct thing is not “to force a universal model,” it is to separate models, each with its own meaning.</p><p>Example with “Product”:</p><ul><li>In Catalog it means name, photos, categories.</li><li>In Pricing it means rates, discounts, taxes.</li><li>In Logistics it means weight, volume, shipping methods.</li></ul><p>If you use the same Product model for everything, sooner or later you break it trying to satisfy all these meanings. Separating subdomains avoids that.</p><p><strong>3 — Events that change state mark domain boundaries</strong><br>When a business event changes responsibility or the “owner” of the next action, there is usually a subdomain boundary there. Events are natural boundaries because they represent a change in what is happening and who decides.</p><p>Quick examples:</p><ul><li>“Payment confirmed” -&gt; the purchase intention stops mattering and shipping logistics begins.</li><li>“Reservation confirmed” -&gt; you move from reservations to room management.</li><li>“Fee charged” -&gt; you move from billing to access.</li></ul><p>These events are perfect for defining boundaries because no one argues about their existence in the business, they are already there, you are just using them as guides.</p><p>If you want to go deeper, you can explore <a href="https://en.wikipedia.org/wiki/Event_storming"><strong>Event Storming:</strong></a> a visual workshop in which business events are placed on a timeline to observe how the workflow is organized. This technique helps identify subdomains and natural boundaries not starting from assumptions, but from the real behavior of the system.</p><h3>Practical procedure</h3><p>1 — List the <strong>main processes</strong> of the application.</p><p>2 — Mark key <strong>roles, terms, and events.</strong></p><p>3 — Propose <strong>domain/subdomain</strong> slices that:</p><ul><li>increase <strong>internal cohesion</strong></li><li><strong>reduce coupling</strong> between areas</li></ul><p>4 — <strong>Validate</strong> it by explaining it to the team. If everyone nods without quizzical looks -&gt; you’re on the right track.</p><h3>From the idea to folders</h3><blockquote><strong>Note on structure:</strong> in Nx and coding projects in general, domains and subdomains often appear as <strong>folders</strong>, not as Nx libraries themselves. From here on, we’ll mainly be talking about subdomains, and more on Nx libraries in part 2.</blockquote><p>Once we have clear domains and subdomains, we can transfer them to code, ensuring that the structure should allow reading the business directly from the file tree, without opening code.</p><pre>libs/<br> app-sales/<br>   catalog/<br>   pricing/<br>   orders/<br> shared/</pre><p>Here, app-sales represents the Sales domain and each subfolder (catalog, pricing, orders) implements a specific subdomain.</p><ul><li>app-sales/catalog -&gt; everything related to <strong>showing and managing the catalog</strong></li><li>app-sales/pricing -&gt; <strong>pricing rules and calculations</strong></li><li>app-sales/orders -&gt; <strong>creation and tracking of orders</strong></li><li>shared/ -&gt; <strong>utilities that don’t belong to any subdomain</strong> (exceptions, helpers, pipes, etc.)</li></ul><p>The key here is that <strong>each subdomain contains its own technical pieces</strong><br> (UI components, services, stores, use cases, DTOs, etc.), but organized by meaning, not by type.</p><p>If tomorrow the discount rule changes, the PR happens in libs/app-sales/pricing, not by searching for files scattered across <em>services, state, </em>and<em> components.</em></p><h3>NxHow do subdomains communicate with each other?</h3><p>Through a <strong>public contract:</strong> types, interfaces, and services that each subdomain exposes from its <em>index.ts</em> file.</p><pre>libs/app-sales/pricing/index.ts</pre><p>Communication between subdomains only happens through that contract. There are no imports between internal folders. There are no shortcuts like ../../internal/model.ts.</p><p>If <strong>catalog</strong> needs to know the final price of a product:</p><ul><li>Import calculatePrice from the <strong>public contract of pricing</strong></li><li>Not from its internals</li></ul><p>In Typescript and Nx this is reinforced with:</p><ul><li><a href="https://www.typescriptlang.org/tsconfig/#paths">Path aliases</a> (@org/app-sales/pricing)</li><li>Rule <a href="https://nx.dev/docs/features/enforce-module-boundaries">@nx/enforce-module-boundaries</a></li></ul><p>This keeps <strong>clear boundaries</strong>, reduces coupling, and makes the code easier to maintain in the long term.</p><h3>In summary</h3><ul><li>The project structure should <strong>tell the story</strong> of the business when you read it.</li><li>A subdomain is not a random folder: it expresses a <strong>business concept.</strong></li><li>Each subdomain <strong>owns its model.</strong></li><li>Interaction between subdomains is made <strong>explicit</strong> through public contracts.</li></ul><blockquote>You can measure whether your architecture is on track like this: someone new to the team should understand the business just by looking at the libs/ folder structure.</blockquote><h3>Next step: Internal anatomy by subdomain</h3><p>Now that we have <strong>the map</strong> (domains, subdomains, and boundaries), in Part 2 we will complete our model with Nx libraries (<em>feature, ui, data, util</em>) within the subdomains, and their dependency rules. With this, we already have a solid foundation for the code to reflect the business language. In the next part we will see how to maintain that order as the project grows.</p><h3>Glossary</h3><p><strong>Ubiquitous language</strong><br>Shared vocabulary between business and development. The names we use in conversations are the same ones we use in code. Avoid synonyms and ambiguities.</p><p><strong>Domain</strong><br>A part of the business reality that we want to model (e.g., Sales, Reservations, Members). It is the problem that the software wants to solve. It is not a folder nor a technical layer.</p><p><strong>Subdomain</strong><br>A natural slice within the domain, where concepts, flows, or responsible parties change (e.g., within Sales: Catalog, Pricing, Orders). Each subdomain encapsulates its own model and rules.</p><p><strong>Subdomain model</strong><br>The set of entities, types, use cases, and logic that only make sense in that subdomain. They are not “global,” because they do not mean the same thing in other contexts.</p><p><strong>Public contracts</strong><br>The stable API that a subdomain exposes to others (types, interfaces, and services re-exported from index.ts). It is the only way subdomains communicate with each other.</p><p><strong>Internals</strong><br>Code private to the subdomain (models, mappers, internal stores, adapters, validations, etc.). It can change without notice. It must not be imported from other subdomains.</p><p><strong>Cohesion</strong><br>What is together because it belongs together. A subdomain with good cohesion groups logic that deals with the same concept.</p><p><strong>Coupling</strong><br>Unnecessary dependencies between parts of the system. We want a high level of cohesion, low coupling.</p><h3>Resources</h3><ul><li><a href="https://www.angulararchitects.io/en/ebooks/micro-frontends-and-moduliths-with-angular/">https://www.angulararchitects.io/en/ebooks/micro-frontends-and-moduliths-with-angular/</a></li><li><a href="https://www.angulararchitects.io/en/ebooks/modern-angular/">https://www.angulararchitects.io/en/ebooks/modern-angular/</a><br> <a href="https://go.nx.dev/angular-patterns-ebook">https://go.nx.dev/angular-patterns-ebook</a></li><li><a href="https://www.google.es/books/edition/Domain_Driven_Design/hHBf4YxMnWMC?hl=en&amp;gbpv=1&amp;printsec=frontcover">https://www.google.es/books/edition/Domain_Driven_Design/</a></li><li><a href="https://www.google.es/books/edition/Domain_Driven_Design/hHBf4YxMnWMC?hl=en&amp;gbpv=1&amp;printsec=frontcover">hHBf4YxMnWMC?hl=en&amp;gbpv=1&amp;printsec=frontcover</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c82290886aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Match de Rust en TypeScript: exhaustividad a lo fácil]]></title>
            <link>https://medium.com/@nijotigajo/match-de-rust-en-typescript-exhaustividad-a-lo-f%C3%A1cil-806f954b614c?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/806f954b614c</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[control-flow]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 14:54:55 GMT</pubDate>
            <atom:updated>2025-10-28T13:20:19.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dww9qbNt6lW0No9d" /><figcaption>Photo by <a href="https://unsplash.com/@tengyart?utm_source=medium&amp;utm_medium=referral">Олег Мороз</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Algo que aprendí leyendo el <a href="https://doc.rust-lang.org/book/ch06-02-match.html">manual de Rust</a> y que me gustó mucho, pero que eché en falta en TypeScript, es la palabra clave <a href="https://doc.rust-lang.org/book/ch06-02-match.html">match</a>. Te obliga a cubrir todos los casos posibles antes de que el código compile.</p><p>Puedes imitarlo en TypeScript con un switch y un pequeño helper. Sin frameworks ni decoradores.</p><pre>type Fruit = &#39;apple&#39; | &#39;banana&#39; | &#39;orange&#39;;</pre><pre>function assertNever(x: never): never {<br>  throw new Error(`Unhandled case: ${x}`);<br>}<br><br>function getColor(fruit: Fruit): string {<br>  switch (fruit) {<br>    case &#39;apple&#39;:<br>      return &#39;red&#39;;<br>    case &#39;banana&#39;:<br>      return &#39;yellow&#39;;<br>    case &#39;orange&#39;:<br>      return &#39;orange&#39;;<br>    default:<br>      // TypeScript se quejará aquí si falta un caso<br>      return assertNever(fruit);<br>  }<br>}</pre><p>Ahora añade una nueva opción y deja el switch tal cual:</p><pre>type Fruit = &#39;apple&#39; | &#39;banana&#39; | &#39;orange&#39; | &#39;grape&#39;;</pre><p>Obtendrás un error de compilación como este:</p><pre>Argument of type &#39;&quot;grape&quot;&#39; is not assignable to parameter of type &#39;never&#39;</pre><p>Ese mensaje es tu comprobación de exhaustividad. El compilador te está diciendo que manejes lo que acabas de añadir.</p><p>Por qué funciona:</p><ul><li>Fruit es una unión de literales de cadena específicos.</li><li>La rama default llama a assertNever. Si todos los casos están cubiertos, el valor ahí es <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type">never</a>. Si añades un caso nuevo y olvidas manejarlo, TypeScript lo marca. No se puede asignar un valor a never porque never representa un tipo que no debería alcanzarse: no tiene valores válidos.</li></ul><p>Uso esto en un proyecto actual en el trabajo para asegurar que, cuando añadimos un nuevo tipo de algoritmo, su implementación esté cubierta en el switch correspondiente.</p><p>¿Qué usarías para esto en lugar de un switch: un mapa de búsqueda, un diccionario de funciones u otra cosa?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806f954b614c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust’s match in TypeScript: Exhaustiveness the Easy Way]]></title>
            <link>https://medium.com/@nijotigajo/rusts-match-in-typescript-exhaustiveness-the-easy-way-dfa3b3b1fec8?source=rss-1d851c92f973------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa3b3b1fec8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[control-flow]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Nico Garitagoitia]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 14:47:59 GMT</pubDate>
            <atom:updated>2025-10-14T14:50:28.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Some Rust" src="https://cdn-images-1.medium.com/max/1024/0*o1erY_xLax087_xd" /><figcaption>Photo by <a href="https://unsplash.com/@tengyart?utm_source=medium&amp;utm_medium=referral">Олег Мороз</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Something I learned while reading the Rust manual and quite liked, but felt missing in TypeScript, is the <a href="https://doc.rust-lang.org/book/ch06-02-match.html">match</a> <a href="https://doc.rust-lang.org/book/ch06-02-match.html">keyword</a>. It makes you cover every possible case before the code compiles.</p><p>You can mirror that in TypeScript with a switch and one small helper, without any frameworks or decorators.</p><pre>type Fruit = &#39;apple&#39; | &#39;banana&#39; | &#39;orange&#39;;</pre><pre>function assertNever(x: never): never {<br>  throw new Error(`Unhandled case: ${x}`);<br>}</pre><pre>function getColor(fruit: Fruit): string {<br>  switch (fruit) {<br>    case &#39;apple&#39;:<br>      return &#39;red&#39;;<br>    case &#39;banana&#39;:<br>      return &#39;yellow&#39;;<br>    case &#39;orange&#39;:<br>      return &#39;orange&#39;;<br>    default:<br>      // TypeScript will complain here if a case is missing<br>      return assertNever(fruit);<br>  }<br>}</pre><p>Now add a new option and leave the switch alone:</p><pre>type Fruit = &#39;apple&#39; | &#39;banana&#39; | &#39;orange&#39; | &#39;grape&#39;;</pre><p>You will get a compile error like this:</p><pre>Argument of type &#39;&quot;grape&quot;&#39; is not assignable to parameter of type &#39;never&#39;</pre><p>That message is your exhaustiveness check. The compiler is telling you to handle what you just added.</p><p>Why this works:</p><ul><li>Fruit is a union of specific string literals.</li><li>The default branch calls assertNever. If every case is handled, the value there is <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type">never</a>. Add a new case and forget to handle it, and TypeScript flags it. A value can’t be assigned to never because never represents a type that should be impossible to reach: it has no valid values.</li></ul><p>I use this in a current project at work to make sure that when we add a new algorithm type, its implementation is covered in the corresponding switch.</p><p>What would you use for this instead of a switch: a lookup map, a function dictionary, or something else?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa3b3b1fec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>