Building production-ready Event-Sourced Node Apps with Ralph-Loop and AI
Event Modeling / Event Sourcing applied · 2026-03-05 · 1ч 4м · 870 просмотров · YouTube ↗
Топики: durable-execution
🎧 Аудио
📝 Summary
model=deepseek-v4-flash · prompt=summary-v7 · 14 346→2 890 tokens · 2026-07-20 15:06:18
🎯 Главная суть
Мартин, автор книги «Understanding Event Sourcing», демонстрирует, как комбинировать Event Modeling с RALF-циклом (повторяющийся запуск агента с очисткой контекста и записью обучений) для быстрой разработки Event Sourced Node.js-приложений. Event Modeling даёт чёткую, независимую разбивку системы на слайсы (кусочки функциональности), а RALF-агент последовательно реализует каждый слайс, обучаясь по ходу итераций. В результате 90% кода генерируется автоматически, а система остаётся поддерживаемой и слабо связанной.
Провал большинства проектов: не технология, а коммуникация
95% успешных систем страдают от «feature explosion» — каждая новая функция увеличивает связность кода, делая изменения дорогими и срывая дедлайны. Основная причина — плохая коммуникация, неверные требования и ошибочные предположения. Самая дорогая ошибка — построить не то, что нужно. Эту проблему нельзя решить технологией, даже идеальной архитектурой микросервисов.
AI как мультипликатор хаоса или порядка
AI лишь умножает текущее состояние кодовой базы: хаотичные системы становятся в 10 раз хаотичнее, хорошо структурированные — в 10 раз быстрее. Беспорядочное использование AI (просто промпты «сделай мне это») приводит к генерации огромного объёма кода с высокой связностью. AI требует ясности: чётких требований, модульности и структуры. Лучшие промпты и markdown-файлы не помогут, если фундамент кода сломан — а это всегда сводится к coupling (связности).
Event Modeling — общий язык для людей и AI
Event Modeling — это простой паттерновый язык, который позволяет описать любую систему с помощью всего 5 ключевых элементов:
- Event — что-то произошло в системе (может быть и не техническим, например, "менеджер позвонил клиенту").
- Command — инструкция системе, при успешном выполнении порождает событие(я).
- Read Model — представление информации, уже имеющейся в системе (для отображения на UI или в автоматизации).
- Screen — UI: какие кнопки, поля, как пользователь взаимодействует.
- Side Effect — автоматическое действие, запускаемое по событию.
Из этих элементов собираются 4 базовых паттерна: State Change Slice (UI → Command → Event), State View (Event → Read Model → Screen), Automation (State View + State Change Slice) и Translation (внешние события для взаимодействия между системами). Каждый паттерн описывается с помощью Given-When-Then, перенесённого из BDD, — это бизнес-правила, которые становятся исполняемыми спецификациями.
Реальные event-модели: масштаб и структура
Мартин показывает настоящую модель из коммерческого проекта — она охватывает десятки слайсов: управление лицензиями, выставление счетов, кейс-менеджмент и т.д. Модели создаются совместно с бизнес-экспертами и AI, но именно человек отвечает за спецификацию. Размер такой модели может быть огромным, но каждый слайс остаётся маленьким, независимым и идеально подходит для AI.
Семифазный процесс Event Modeling
На практике за один workshop проходят 7 фаз. В видео показана сокращённая демонстрация на примере To-Do приложения:
- Сбор требований (брайншторминг событий).
- AI помогает построить timeline — читаемый поток событий.
- Затем — наброски экранов (не более 2 минут на экран, сознательно «уродливые»).
- Создание слайсов: для каждого шага определяются команды, события, read-модели. Проверяется information completeness — если между элементами не хватает атрибутов, система не считается готовой к реализации. Например, если событие
ToDoListCreatedтребуетname, но не указано, откуда он берётся, — это красный флаг. Такая проверка предотвращает блокировки на месяцы вперёд. - Для каждого слайса пишутся Given-When-Then (бизнес-правила). Пример: "Given to-do list уже существует; When я пытаюсь создать ещё один с тем же именем; Then ошибка".
- C готовой моделью можно чат-верификация — AI отвечает на вопросы по модели, что помогает выявить неясности.
RALF Loop: суть и отличие от других реализаций
RALF Loop — это простой bash-скрипт, который:
- Берёт index.json (экспортированный из Miro) со списком слайсов и их статусами (created, planned, in progress, done).
- В каждой итерации находит первый слайс со статусом
planned, реализует его, записывает в progress.txt действия и обучения (learnings). - После завершения итерации очищает контекст (в отличие от ранних реализаций Antropic), а все накопленные обучения сжимаются в agents.md.
- В начале следующей итерации агент стартует с чистым контекстом + файлом agents.md, содержащим все предыдущие знания. За счёт этого агент становится умнее с каждой итерацией, а не деградирует из-за захламлённого контекстного окна.
- Мартин специально не использует встроенные RALF-реализации от Anthropic/Claude Code, а написал собственный скрипт.
Настройка для агента: Claud.md, Agents.md, Skills.md
Проект содержит три типа markdown-файлов:
- Claud.md — статические базовые настройки: структура проекта, используемые технологии, правила форматирования.
- Agents.md — полностью AI-генерируемый файл, куда из обучения попадают gotcha’s, паттерны, уточнения по типам, командам npm и т.д. Не поддерживается вручную.
- Skills.md — описание, что такое слайс каждого типа (state change slice, state view slice, automation). На их основе агент интерпретирует JSON и знает, какие файлы создавать (routes, command, events, test cases).
- Prompt.md — промпт, который определяет 17 задач RALF-цикла.
Демонстрация: To-Do приложение за 2 слайса
Мартин вживую запускает RALF-цикл для небольшой event-модели To-Do:
- Экспортирует из Miro index.json и .slices/*.json. В index.json каждому слайсу присваивается статус. Два слайса («Создать список» и «Просмотр списков») помечаются как
planned. - Запускает
ralf.shна 10 итераций. Первая итерация заняла около 30 секунд: агент сгенерировал для первого слайса:- routes (Express с OpenAPI-спецификацией),
- command со всеми полями,
- test cases (по умолчанию, если в модели нет Given-When-Then — агент генерирует сам, но если спецификация есть — строго следует ей).
- Дополнительно генерируется ui-prompt.md — файл с описанием API для фронтенд-агента. Фронтенд-агент может использовать этот промпт + скриншот экрана из Miro для генерации UI.
- Вторая итерация сразу перешла к слайсу «To-Do list» (список существующих списков).
Статическая кодогенерация vs динамическая
Мартин использует статическую генерацию кода (шаблонизатор emmet-superbase) для создания скелета приложения. Это надёжно, так как все слайсы идентичны по структуре. Однако в демонстрации RALF-цикл генерирует код полностью, опираясь на Skills.md. Статическая генерация и RALF могут сочетаться: статический код даёт 80% структуры, а RALF достраивает остальное (бизнес-логику, тесты), не тратя лишние токены на повторяющиеся элементы.
Независимость слайсов — ключ к масштабированию
Каждый слайс — это крошечный, самодостаточный модуль (почти микросервис). Единственная связь между слайсами — события (команды и события). Это позволяет:
- Запускать множество RALF-агентов параллельно в одном репозитории, не мешая друг другу.
- Добавлять больше разработчиков без замедления проекта (закон Брукса не работает при слабой связности).
- Генерировать код ночью: проснуться утром с 50 готовыми слайсами.
Реальный проект: 90% кода через AI
Мартин показывает код реального Node.js-проекта, где все слайсы (десятки) сгенерированы через RALF. Каждый слайс имеет три файла: routes, command, test cases. Все они выглядят одинаково — «dead boring code», что и нужно для поддерживаемости. Проект использует Emmet (Node.js event sourcing framework), Express и React.
Отвечая на вопросы зрителей
В ходе демонстрации участники задали несколько уточняющих вопросов:
- Сравнение с реализацией Anthopic (C compiler): Мартин отметил, что ранняя версия Antropic не очищала контекст, что приводило к деградации. Его подход (очистка контекста + обучение в agents.md) — развитие этой идеи.
- Привязка к фреймворкам: для JVM/Axon Framework нужны лишь другие skill-файлы; Claud.md и RALF-скрипт остаются теми же.
- Спецификация для AI: информация о слайсе передаётся через .slices/*.json (поля команды, события, типы, Given-When-Then). Дополнительные инструкции в Skills.md. Никакого специального «декодирования» JSON не требуется.
- Ограничение токенов: RALF-цикл выполняется ограниченное количество итераций (обычно 10). Если токены заканчиваются, цикл просто останавливается, и можно продолжить с последнего сохранённого состояния (статусы слайсов).
📜 Transcript
en · 11 140 слов · 140 сегментов · clean
Показать текст транскрипта
so the headline is building production ready event sourced node apps with ralph lube and ai the first task was can i can i build a headline for a webinar purely out of buzzwords yes i can look at that it's beautiful well beautifully well so um what i want to show you today is just a little bit what what happened in the last few weeks i was asked by a client um can you build a node app with uh event so can you build an event source node app and it turned out yes that works beautifully well and um yeah we had limited budget limited resources and uh what you see today in this webinar is just what came out of this how we built this and i just want to give a little bit of project feedback how how that worked out so um yeah at the end of the workshop you'll get the full setup you see in this workshop so you it's ready to use you can start building in less than a minute you can just check it out run the ralph loop what the ralph loop is you will see during this webinar and then you it will just start to build hopefully so um stay until the end it might be worth it and what you also see in this webinar i'm not sure if you are familiar with event modeling but i will show you two real world event models which have a decent size so it's typically when you work with event modeling you oftentimes see small examples i show you some real event models from real projects and then you see how big they can get and how typically i structure them so who am i if you don't know me i'm martin i wrote a book it's called understanding event sourcing and basically what you see here in this webinar today is exactly what is written in this book Typically, I am not a Node guy. I made a few Node projects, but most of my projects are on the JBM. I work with Java, I work with Kotlin, I work with the Spring framework, and I work with the Axon framework. That is my typical stack. But this time, I work with Node. And guess what? The same patterns I use on the JBM apply to the Node project. It's the very same thing. And it's all written in this book. The whole process is written in this book. And the patterns in this book apply to any tech stack. And this is really the proof. So my whole career, I worked in the education space. I trained more than 1,500 people, many of them in person. So I'm giving workshops all the time, helping companies, adaptive event modeling, adaptive event sourcing. That's really what I'm really, really passionate about. That's also why I wrote this book. and what i really love about giving workshops is the feedback that was mackie uh he gave a feedback and he called me the defogger and i really liked that because after the workshop some it seemed like some of the forks got cleared so as i said i have companies adopt event modeling and event sourcing um it's still a niche but we get quite some traction with all those beautiful patterns event modeling and event sourcing provides because it's an enabler for ai if you want to work with ai you need well-structured systems and event modeling and event sourcing they allow you to give this structure to systems and you will see today how i structure those systems and why it works so well so um yeah when i'm giving workshops many many people come to me after that and say and they had these aha moments especially when we talk about the systems um oftentimes what happens is the people realize the system we are building we don't need to build this at all because it doesn't make sense that's the best outcome you can get out of a workshop okay today what i will show you today is how we break down a system into small building blocks without writing hundreds of jira tickets so if you work with event modeling your jira tickets are either non-existent or if you still work with jira typically they are just headlines no details because all the details are in the event model and i will show you how to break down those systems i will show you also how i clearly define what each of those building blocks should do without spending weeks in requirement meetings I will also show you how to prepare 80% of the code structure without spending a single token of your AI budget. What I do is I combine AI code generation with static code generation, and this gives really, really good results. I will also show you how I use AI agents to build the rest, more or less on autopilot. I'm using a technique called the RALF loop. Most probably you've heard about the RALF loop. It's been everywhere. but um yeah i will just show you how i apply it and why it's such a beautiful combination with event modeling so and what you will see is agents love what we are doing with event modeling they absolutely love it because it's exactly the level of abstraction they need to work so the architecture i will show you today runs exactly like this in production for many systems and now also on different stacks. So for example, the node stack. The stack that I will show you today is of course event modeling for specifications. We use Emmet for event sourcing. Emmet is a node event sourcing framework. It's open source, freely available. Now we will use that. Of course, node is the runtime. We use Express as an API layer and React for the client. That's the whole stack. this is a dead boring step and that's exactly what it should be typically my source code and also my projects they are dead boring they do the same thing again and again and again and if you look at the source code it's really a boring thing and that's exactly what it should be writing creative code is not my job i write very very boring code and i'm doing very well with it Let me give you some background quickly before we jump in. What does that actually mean? Why do I talk about event modeling all the time? Why do I talk about event sourcing all the time? And why did I write this book in the first place? Back in 2021, I was really, really annoyed with our whole industry, how most projects I was involved with worked. I couldn't take it anymore. It was really, I was really... really annoyed with all this and i really thought about quitting the industry at least thought about quitting the whole development space maybe getting some becoming some kind of an agile consultant or something i was just annoyed but then just in time i read an article and this article changed really everything for me it was one article i've read and this article changed how i look at systems how i think about systems it changed literally everything and it was the article that introduced the web modeling and this was really the missing piece i was looking for um that that that was missing it was the missing piece so it was really one single article and i remember very well when i read this article i couldn't sleep i read this article and this was exactly what i was looking for because finally it all made sense it all started to make sense The problem in most projects I was involved with was never technology. So we couldn't solve it with technology, no matter how well you design your microservices, no matter how well your code is structured, no matter how much you think about architecture. The root of the problem was never technology, and we cannot solve it with technology. When I understood that, everything changed. So what's the real problem? 95% of our successful software systems, they suffer from feature explosion. Feature explosion. why are only successful projects because nobody is adding features to unsuccessful projects but if you if you have a successful project typically what you do is you add one feature after the other feature customers request new features and you add one feature after the other the more features we add the more coupling we get right that's physics that's a law of nature at least so i thought that's what i thought well just if you add more features the more features you add there's more source code more stuff you have to take care of you have coupling in your source code coupling in your whole code base you need to change more things i really thought that that's what it is that's what software projects look like but that's a lie that's not true there's a different way to do that and this is also the big enabler if you ask me the big enabler to work with ai in your code base i will show you what that means that's the typical curve you see in most projects so the longer you work in the project the more expensive each feature gets you need to name the features get bigger and bigger but you don't necessarily deliver more value and if you look at the the cost curve the longer you work in the project just the more you need to pay for it that's just how most projects look like the problem with this is deadlines move which means we miss planned campaigns we break our deadlines and we break our launch dates and everything becomes super expensive and this repeats again and again in most projects budgets explode and this can kill a project before it's even launched i've seen this multiple times the root of the problem though is bad communication bad requirements and wrong assumptions this triplet is really the the uh the horror for every project most expensive the most expensive mistake you can do build the wrong thing and this happens again and again you build the wrong thing because people don't communicate people don't talk to each other and you think you understand the problem you're trying to solve but it's not the case oftentimes people don't understand the problem and they build something just to realize a few months into the project well this is completely wrong we solved the really wrong problem and that's the most expensive mistake you can make in any project building the wrong thing is the most expensive thing you can do misunderstood requirements typically lead to wrong features being built which typically lead to expensive rework which lead to your first cracks in the architecture and no matter how good your architecture is if that happens typically you are already declining there's nothing you can do about it but what about ai everybody's talking about ai right everybody at least on linkedin If you leave LinkedIn, the bubble is not that big. But if you are on LinkedIn, that's crazy. Everybody is talking about AI. Well, if you ask me, whatever you have right now, AI just multiplies it by a factor 10, at least. You could also say by a factor 100 or by a factor 1,000. So if your current architecture is chaotic with AI, you just get 10 times more chaos. If you have a well-structured architecture and a well-defined process, AI just makes you 10 times faster. So it's just a multiplier of what you already have. Typically what happens when you start using AI is you prompt something, well, build me this, and you hope to get something out of it. Typically that happens, you get something, but this, what you get is typically not maintainable. At least if I work with this like AI, with AI like this, What I get is a whole bunch of code, typically. And the more you prompt, the more code you get. It's really crazy. And this didn't change with the newer models. So this is still the case. You get a whole lot of code and typically much more code than you need to solve a problem. And the result is typically a whole lot of coupling in the code. Coupling is the big problem in most code bases. It's not how you structure it. It's really coupling. Coupling is the big problem and also the problem that most agents face when they get into those code bases. What AI truly needs is clarity. You need a lot of clarity in your code base. Clarity means structure. Clarity means modularity. But clarity also means very, very clear requirements and instructions. Typically, you don't get clarity with better prompts. I see a lot of teams right now trying to improve their prompts and everything. But if your code base is not well structured, no prompt will help you. That's at least my experience. You can invest a whole lot of time in your prompts. If the code base isn't ready for AI, no prompt will really help. And what also will not help is if you put more markdown files. into your code base not sure what what your day looks like um nowadays but uh just a few years ago my job was to manage code structure code nowadays it's more like manage a whole lot of markdown files at least in many projects that happens i'm not sure i really like that markdown managing markdown files is really not what i want to do all day but right now this really happens almost everywhere Everybody tries to get those instructions ready for AI using Markdown files, different agents MD, Claude MD, and skill files, whatever you need for your AI agents. As I said, but you can't build a stable AI on a broken foundation. This simply doesn't work. AI breaks when small changes cascade through your code base. And that's just another word for coupling. Couplings, no matter which problem you face in your code base, it almost... always boils down to coupling coupling is really the root of most problems you face and then i hear people say what about the new token window now we have opus 4.6 it has a 1 million token window this doesn't really help and i can tell you i wasn't impressed at all by a 1 million token window because i typically i don't need that if your code base is well structured you shouldn't need a 1 million token context window Think back about Bill Gates. He said 640K ought to be enough for anybody. Well, if you translate this to today, how much context is enough for everybody? How much context do you really need? Well, I think we are still looking for the answer to this, but it's not necessarily more is better. I don't believe that. So where does this all lead? Why am I talking about all those problems you most probably know already? Where does this all lead? Well, let me tell you a different story. what about and it's the same thing that is in this book so it's the very same story what if we describe a system in great detail but we do it in a language that anyone understands including your ai agents so if you can describe a system in a language that both your engineers understand both the business people understand and also your ai agent it's the same language for anyone wouldn't that be beautiful what if we use only five key elements and four patterns to describe any system in the world that's exactly what event modeling is it's a very simple pattern-based language that allows you to describe all those systems no matter how complicated they are so let me quickly give you a very very brief introduction to event modeling so you know what we're talking about here because event modeling is a fundamental piece of how i build systems it's actually it's the biggest piece because i spend most of my time nowadays in miro i'm a software engineer by heart but most of my time i spend in miro i don't spend it in code i spend it in miro specifying how systems should actually work not writing the code this is what ai can do very well but specifying the system that is where we need really real engineering principles and i work with miro and you see that in a second how that how that works and i just use these five key elements uh in event modeling the first one is an event an event is just something that happened in our system Well, it's not something technical. When people hear event, they immediately think about event sourcing. They think about event-driven architectures and stuff like that. Nothing like that. An event is just something that happens in the system. An event could be that your marketing agent called a customer. A completely manual process. Still, this is an event, and this would be an event in the event model. This has absolutely nothing technical to it. The next thing we have is we have a command. Command is just an instruction to the system. Something should happen at the result of a command, if it's done correctly, is typically an event or several events. So they belong together. Then we have a read model. So the read model is just making sense of what already happened in the system. A read model just shows you how is information already available in the system used. How do we provide this information to a UI? How do we provide this information to an automation, for example? And what is an automation? It's just like a background process. then we have um screens what is a screen well just how do users make things happen in the system well what buttons do we have what input elements do we have what is the ux of our system and last but not least of course we have the side effects what of what already happened in the system uh you have an event and based on that event something happens automatically in the system this is all all i need to describe any system in the world you don't need more than this just these five elements and if you combine these five elements into four simple patterns you can really describe any functionality so the four patterns are simple one is a state change slice we call them slices a state change slice is just basically a combination of a ui a command and then one or several events basically how does information get into the system the next one is a state view So state view just means we take all these events which are already in the system. And remember, this has nothing technical to it. It's just information that is available. How do we use this information to, for example, display a screen? Or how do we use this information to trigger an action in the system? This is what an automation looks like. Automations is basically just a combination of a state view and a state change slice. It's just two slices. We use information already available in the system. Then there is this automatic process. And this automatic process is triggered by a certain state change in our system and the last but not least we have translations oftentimes we not only talk about one system we talk about many systems and we are especially interested in how do these systems interact with each other now for this i use external events external events are yellow so whenever you see an external event a yellow event in an event model you know there's data from it from another system entering our system our bounded context for example That's all. These are all the patterns I use to describe any system in the world. And the great thing is, if you work with these patterns, what happens is you naturally divide the system into what we call slices. You see here just a set of slices that describe a business functionality. One slice after the other. And these slices are so small that they are perfectly for AI. ai works with those slices and you see that in a second how that actually works but using event modeling you break the system down into natural functional building blocks with the perfect size for ai but to work with ai we not only need the functionality we also need the business rules what are the business rules in our system so if you click on a button Of course, you can describe the functionality. Oh, if you click this button, there is an email that gets sent out, for example. But typically, if you have this functionality in the system, there are business rules behind that functionality. So in event modeling, what we do is we use given when then. Of course, stolen from behavior-driven development. We describe the system and the business rules using given when then. So here's a simple example. Given, nothing happens yet in the system. we just started the system when i reserve this ticket the ticket should be reserved there should be a new reservation in the ticket same thing given the capacity limit was reached for my ticket reservation system when i try to reserve another ticket there is an error that doesn't work this way this way you can describe any business functionality just by using these five elements here but how do we now combine this with ai What I will show you today is how I do that. It's called the Ralph Loop technique. So maybe you remember Ralph Wiggum from The Simpsons. It's a very simple character. And the Ralph Loop is a very simple approach. The whole implementation of Ralph Loop is this. The whole idea of Ralph Loop is you run your agent in a loop again and again and again and again. And you give it the same prompt again and again and again. Sounds crazy. And many people, because I write quite a bit about how I use Ralph Loop on LinkedIn and in other places, and many people approach me and ask, what's the point? What's the point of Ralph Loop? I don't get it. Running your agent in a loop? I don't get it. And that was exactly the same what I also said. When I read this article about Ralph Loop, I didn't get it. What's the point? This is the point. After each iteration in your loop, you clear the context this prevents context load after each iteration you clear the context this means your agent is starting with a clean context every single time when you run it in a loop and another very important thing i'm talking about ralph loop we record the learnings in each iteration so whenever you run a loop there is a text file where your agent just appends oh this is what i learned in this iteration and in the next iteration we add more learnings to this file so your agent is learning in each iteration and this makes all the difference because now it's not no longer the case that your agent gets dumber and dumber the longer you work with it because the context fills up no your agent gets smarter and smarter with each iteration in each loop because you add those learnings and in the next iteration you have more learnings and in the next iteration you have more learnings so the longer you work with your agent the smarter it gets you record all those learnings again and again and they apply to your project and it's really it's almost magical how well that works so what we do now is we'll model a system together we jump um yeah now to miro i will show you how i model a system very quickly some boilerplate code using a static code generator i'll run the ralph loop and we'll build some slices let's see how far we can get with this we'll generate the front end with just one prompt and after that i'll show you um the event models and of course at the end we have time for q a so the whole idea is not to build this whole system what i want to do is i want to really show you the process how i use those tools how i combine those different elements together and why it works so well for me. And of course, if you have questions, feel free to ask questions at any point in time. I will never stop talking. That's typically what happens in my webinars. I talk all the time. If you have a question, just shout it out. Interrupt me at any point in time. So let's jump to Miro. So first of all, what we do here is we have a simple use case prepared so there's no code prepared nothing so we will really start with a very simple thing that's our requirements that's typically how projects start very simple requirements now what typically happens is we go through seven phases and i will share this uh mirror board after the webinar so you can access this if you look at the mirror board here There's a whole lot of information available about event modeling, about the seven phases of event modeling. So if you want to apply event modeling to your project, this is how you do it. Typically, you run through seven phases in each and every event modeling workshop, and it's all documented here. So this is a great starting point if you just want to give it a try. The first thing we typically do is we do the brainstorming. The brainstorming just means get a whole bunch of people in the project together and try to extract as much knowledge as possible. onto this board by just um finding all the events that could happen in the system that's all we do in the brainstorming we do we cheat a little bit today because what i will do is i will use a little bit of ai to speed this process up so what we have here is we have our requirements here it's a to-do application very simple so i intentionally chose a very simple use case it's a to-do application typically what happens if i get the list of those requirements the first thing i do is i build a timeline out of that with ai because it's much easier to read a timeline than to read all this text so let me see if that works now i will just copy this thing here and we will start over here what you see on the left side that's the event modeling toolkit that's a mirror extension to use event modeling in miro so um you can do event modeling without any tooling you don't need the mirror toolkit extension but this is just a tool that helps you a little bit and does things a little bit faster so what i'm doing now i just paste the requirements here and say give me a timeline It will now analyze the timeline. In the background, there is an AI that knows how to pass requirements, that knows how to understand requirements, and it will give me just a timeline here. And it's so much easier to read this timeline than to read all this text, because now if we look at that, I know, okay, what is written in those requirements? There is a to-do list that gets created. Nice. there is an item that gets added to the list also a nice item marked is closed item can be deleted and the to-do list can also be deleted that's all that's our whole requirement here very simple now what what happens next typically in an event modeling workshop when we have our timeline we try to build the first slices just by understanding what is happening in the system and the next step i typically do is i draw some screens screens are a very essential part in event modeling and screens that i draw are intentionally very ugly so my super skill is drawing ugly screens i'm perfect in drawing ugly screens so let's see and my rule of thumb is i never use more than two minutes for a screen if you need more than two minutes to sketch a screen you're definitely doing it wrong so this is my to-do lists and we would provide something like a name here with an input field like this and a button to save that's all that's my whole ui and if we save the to-do list i want to have a list of lists here down here my list number one My list number two, my list number three. Just a list of already created lists. So I can maintain a list of to-do lists. Nice. That could be my screen. And now what we do is we would step by step decide what is necessary to build this screen. So we use the events, we use the screen, and then we just decide what is the information that is necessary and how do we get this information into our system. So in this case, the first thing I will look at is how do I get this list into my system. What is relevant for this? And I always mark this in the screens like this. So it's really clear, okay, for this step in the system, these are the elements which are relevant. The input field and the save button. Everything else, I don't care. I only care about this. So what happens if a user clicks this button? What we do is we fire a command into the system, and this command could be named at list, for example, something like this. In event modeling, you connect the elements. So you do it like this. The arrows between those elements, they show you how information flows. So here we see information is flowing from the screen to the command and from the command to the list. What you also get with this tooling here is information completeness. Very, very important feature in event modeling, information completeness. At any point in time, you need to be clear about... information completeness is my system information complete or not this prevents you from making wrong assumptions assumptions is one of the biggest problems you face in your typical project here we see for example this arrow is turning red why this is not information complete the to-do list created event states i want to have a name attribute but we didn't define where this information is coming from same example for i just had that recently there was a requirement where we need the user email and for the user email we do the registration in our system it turned out nobody knows where this user email is coming from you cannot start with the implementation if you are not information complete because it could be that this user email is coming from a completely different system and maybe you need an api endpoint with a team that has a backlog with filled with three month worth of work so you you will only get your new api endpoint after three months this can block your whole system just because you didn't do the app from work to check is my system do i have all the information i need so i'm very very strict about information completeness you cannot start with your work until you are information complete so in this case what would we do very simple the name is provided by the screen so we can just copy copy the information here it gets provided here by the command and it also gets provided by the screen here this is our first slice we just defined our first slice this could already be implemented now what i could do is i could say i make this a slice a slice is just a border around this functionality here but you could already implement this you could already implement a screen you could implement the api endpoint to accept the command you could implement the persistence here this could be event sourced this could be anything else event modeling is not about technology not at all But today, of course, we will look at how to build this using an event sourced app in Node. So, of course, in our case, this will be an event sourced system. And the great thing is, if you combine event modeling with event sourcing, there is a one-to-one translation between your event model and the code. So, it's very easy for static code generation. It's very easy for coding agents to translate the event model into code. Let's define a second slice here. Because, of course, If we add an item, we want to update this list here. So in the next step, what I would do is I would just mark this list here. And this is in green because now we are not giving information into the system. We are using information already available in the system, for example, to render this list. For this, we need a read model. So the read model here is just something like available to-do lists. something we will only model this slice here so this is not about event modeling alone i just want to show you how you typically go step by step in your system and then what you would do is you would just connect the event to the read model the read model to the screen and make sure that you provide all the information in your screen so what do we need what information do we need in our screen it's the name of this to-do list here And of course, again, we are not information complete. So we don't provide all the information. But in this case, again, we can make it very simple. We just copy everything. And this should hopefully work. No red arrows means we are information complete. So this would be my second slice. So last thing I want to show you is how do we define the given when dense? So in this case, we could have a rule, for example, that states I don't allow. to-do lists with the same name in the system so a rule could be just using a given one then i could say given the to-do list was already created when i tried to create another to-do list with the same name then i have an error which says um can't have lists with same names something like that spend a lot of time in event modeling defining those given then then and defining those business rules because this is what's really really valuable and we don't do this um alone we do this collaboratively together with business experts together with people who really really know how the system works and the great thing is if you do it like that you can even start to chat with your requirements and verify that so let's see if that works so for example i just need to give it a context for this so this is my uh sample to do context and i will add those slices to this context bear with me for a second now what i could do is i could just check with my requirements and see does this does this make sense so i could say this is the sample to do and i can just ask are there any rules to add lists for the event model just analyzes this and you can chat with your requirements and this is really really great if you have a bigger event model you can just chat with your requirements using ai to verify what you modeled and sometimes if the ai doesn't understand what you what you're doing typically your model isn't clear enough that's a very good indication if you if you are on the right track so if you model this to-do application i did that before before we jumped into the webinar this this is something how this um could look like how this event model could look like so here we have the ui for creating a to-do item we fire this command here then we have just to do this created event and so on and so forth so in the end if you do event modeling right you can read the whole system basically from left to right you start on the left and if you want to know what happens in the system you go step by step slice by slice to the right that's typically how it works so let me just remove this status here because we want to start from scratch so now if we have the system here and it's fully specified and you also see that there are quite some business rules here so for example one business rules we have in the system is i can only have three to-do items in one list the given when then for this would look like a given to-do list created and given you have i have three item added events if i now try to add another item i have an error i can only add three items and again you could just ask ai does that work is that model correctly uh let's see if that works how many items can i add to a list you can add a maximum of three items to the list the email just looks at the agent just looks at the event model and sees these are the business rules that are defined very cool you can chat with your requirement and that's really a really an interesting way to work but How do you now translate this to code? Now, if you've done it correctly, you see the event model. But how do you get from the event model to code? And let me quickly jump over to a real-world event model just so you see how big they can get. This is a real-world event model. That's a real project. So let me zoom out. That's what a typical event model looks like. So you have different use cases here on the board. defined step by step, slice by slice, including the business rules. So it's not only on a small scale, this can happen on a very, very large scale. So here, for example, this down here is license management. This is invoicing, all different use cases, but everything is on the same board. Here is case management. You see that that's a lot. Step by step. This model is built together with business experts. This model is built partly with AI, but the whole system is described in the event model here. And if you zoom out, it's really big. And this is still a work in progress. This is not done in the use cases down here. You see a lot of screens. This is where we currently have discussions. How should that look like? How could that look like? That's how we are working with it. So how do we get to code from here? How do I use this together with AI? Now, let's see. What you can do here is you can export this configuration. And that's exactly also the configuration you'll get in the demo. repository so you can export this whole event model here and what you'll get is a big big json there's a lot of json in here and this json is just describes slice by slice what is specified here in my event model and the great thing it turns out this json is the perfect input for a ralph loop now let me just export this um it should already be available and let's jump over to intelligent quickly so if you export this what you'll get is first you get this gigantic config chasen so just for this small model here it's already it's a ton a lot of stuff in here everything that happens in the event model is described in this chasen but what you'll also get is you'll get a breakdown in one file called index chasen and that's something that's an addition that i added because of ralph loop that's basically your input to the ralph loop you see here that's all the slices which are defined in my model But every slice here has a status. So here, the status here is created. There's nothing to do for a rough loop because the rough loop is basically, it's just, it's looking for slices which are in status planned. That's the tasks. So just think about it. It's running in a loop and it's looking at this index.json and it also always looks, is there one slice in status planned? And if that is the case, the slice gets picked up and gets implemented. That's how I use it. um first do some static code generation and then let's start the raw food i just want to show you how that looks like so i work a lot with static code generation because it's very very reliable and it turns out if you have a well-structured system you have repeating patterns all over the code base especially when you when you work with slices and you when you work with event sourcing those patterns repeat again every slice is just a copy of another slice it's perfect for static code generation now let's just start this code generation and you can also use this with the demo repository you get because everything is is available in there including those code generators you can just run it exactly as i'm doing it right here so the code generator i'm using here is called emet super base because this is specialized on using super base but you don't have to use super base to use this uh this is broken why is this broken because i'm in the wrong folder so what i do now is i create the skeleton app the skeleton app is just um the the template application for everything but there is no no no code that gets generated it's just a template and what you also see here is you have the prompt that's the prompt for the ralph loop and you have the ralph loop itself the ralph loop is just it's a bash script so i'm not even using the built-in ralph loop with that you get with entropic and with cloud code it's just a simple bash script it's running over over and over this index.json and looking for slices which are in status planned And if there is a slice and status planned, the loop picks it up and implements it. That's how it works. And the great thing is we already have the guardrails defined for the agent because we have the given when thens here. The given when thens are the guardrails for the agent. You can generate them statically. That's what I typically do. You can also let the agent generate the code, but the logic, the business logic is defined here. And this is a perfect guardrail for AI because we just need to generate this test case and run it. and if it's green and it works exactly like specified here in the event model you can be pretty sure that your slice works because you didn't define those test cases alone you defined them together with the business experts basically your business knowledge becomes an executable specification in code that's the best thing you can get let's see if that works so first thing i'm doing not doing now is uh i would just say what is the slice that we start with let's just start with create to-do list i want to implement i could mark them all as planned if i wanted to and i could just call it a day come back tomorrow and look at all the generated slices but that's typically not how i work sometimes i do um overnight but let's just say we want to have two slices implemented create to-do list and the to-do lists slice here i export this again Let's go back here. Let's quickly check the index.json before we start the RALF loop. So we see here, we have now two slices, which are in status plant. All the other slices are still in status created. And now what I'm doing is I just start the RALF loop. You see here, typically, if you don't put in anything, it's 10 iterations that it does. So after 10 iterations, it typically stops. And now we can just wait and see if we get a little bit of response here. If you just wait a little bit, maybe about 30 seconds we should see the agent pick up the first slice and implement it in the meantime are there any questions i could answer until we get a feedback here we still have 15 minutes hi martin good quick question did you generate the code with the code generator for the two slices or this ralph is going to do it so typically typically i i use a static code generator in this case now um it's just um i let ralph generate the whole thing the whole slice including the scenarios Okay, thank you. So no templates or patterns for it to follow? So it generates freely from the specification? No, there is templates. So yeah, good point. no of course there are templates so what we have is and there's there are skills defined for each slice type there are skills defined and how to build a slice there's a there's a skill for state change slice there's a skill for a state few slice there's a skill for an automation slice so there's there's absolutely no room for interpretation it's absolutely clear what a slice looks like and typically it does exactly what is specified here and now what you see here in the ui just quickly we see picked up the first slice um status went from plan to in progress which means um ralph is currently working on exactly this slice and it picked the first to do the create to-do list slice so typically i don't specify which slice to pick and if you look at the prompt it says pick the first slice that makes the most sense so when from all the slices which are currently in status uh planned just pick the one that makes the most sense and if you want to go really crazy you can of course run as many ralph loops as as you want in parallel so you don't have to run it just with one agent you can run as many agents as possible that also works with developers so the great thing is if you have those slices and those slices are independent from one another that is the really important part and that is why it works those slices are completely independent from one another and this is why if you work with a sliced architecture like this and with event modeling adding more developers or more agents to the project makes the project faster not slower any other questions i could answer while ralph loop is working yes so do you make an mcp to get the feedback to the my road or do you use myroai directly there's no there is no mcp server here it's really just there's a docker container running locally and this docker container provides an api and this api gets red here so there is no mcp server or anything like that so it's the viral api that gets used no that's the mirror extension here the mirror extension here just the queries this status okay so it goes through okay okay so it can communicate with the dark container which is connected to here yeah okay yes exactly I believe you know this use case when Antropic created a compiler for C, like recently, and they had the similar RALF loop, but different from yours. Have you compared your implementation and their? So the first implementation in Antropic was not usable, because what they didn't do is they didn't clear the context. so the longer you ran those those loop the the the your context filled up over time i think they fixed this in the meantime but i don't see a point in this so i'm really just using this i don't know i mean in the article they posted they even didn't use the rough loop of the cloud code they used like some bash script or something like this so similar like yours but yes yes but a little bit different. So I was wondering if you compared your implementation in there. They even run it in parallel using work tree or something like this. Yeah, but a little bit different than yours. I mean, there are many, of course, there are many, many scripts for Rolf Loop and I adjusted the script to my requirements because I have this JSON file, I need to read this JSON file and stuff like that. So, of course, I adjusted it. But I guess in essence, it should still be the same. Yeah, the idea is similar. The idea is similar. Yeah. and of course you can using work trees you can run really as many agents as you want and you could even run the same agents in the same workspace you don't even have using this approach you don't even have to use different work trees they can all run in the same uh in the same repository because those slices are independent so this would also work but of course i mean you you want to if you want to commit and stuff like that um it would still make sense but just from a code base you can run all those agents in just one in one repository all right what else any other questions so it's still it's still implementing here it takes quite long let's see what what's going on here hey martin i've got a quick question yes of course so the so to make sure i've heard of the ralph loop i don't fully understand it so what's happening here is you're you're feeding it the same data but it's updating this this file here and something's been completed you clear out the context and it's just starting from scratch taking the next one that's not completed and doing the thing yes okay that's it that's that's all that's the whole idea that's great and you see here that the first the first iteration is done so the first slice is implemented so if we jump now here um it should hopefully refresh in a second so it's done and it should now pick up the next just automatically so we can have a look at the we can have a look at the at the generated slice so it generated the create to do list slice and you see here all those slices they all look the same so if you look at another project all those slices look the same they have the same three files every time it's really crazy how simple that is now what what i do is what gets created here we have a routes file that's for express that's the api this routes file has an open api specification that all is all defined in the skill file and you get the skill files um with the repo i sent you so it's all in there you can really just you can do it exactly what i just did Just run the RALF loop and it will start to build. Here you have the command that got generated with all the files, everything in here, and also the test cases. So I didn't specify any test cases. So in my prompt is specified if a slice has no test cases, the agent can make test cases of itself. I will review it and maybe delete it. But if I don't specify any test cases, the agent is allowed to do that it's not the case if there are test specifications defined then it just has to do what is specified in the model that's how i currently use it and for me that works quite well what also gets generated is um so this is this is the backend agent so this is the backend agent this generates the slice for the backend what this agent does is it generates a ui prompt md and this ui prompt md is the input for the ui agent of course you also want to have an agent that works on the ui so if you want to create the ui and there is an api this ui prompt um describes which api endpoints are relevant so this is uh using a rest api you have all the api endpoints in here you have the payloads in here everything is described here necessary to build the ui what i typically do is i make a screenshot of the of the screens in the mirror event model post paste it also here because unfortunately you cannot query those screenshots with an API that doesn't work so if you want to have give it more input you can use the screenshots I just paste it here and you can render the UI agent and this builds the UI based on the specification here and this works we are also really really well so we are now in iteration two of ten you see here the next slice is picked up now it's working on the to-do list that's our second slice and you can just you can just leave you can you can keep it running so if your structure is well defined and if everything is well defined you can just keep it running overnight build all the slices here and just rev you tomorrow when you come back let everything work and this is what i very very often do it's really amazing now if i let me quickly show you um a bigger project i'm using this approach just want to show you the code structure how that looks like So here you see that's a bigger project. And here you see the slices. Let's move this down a little bit. Same approach, same structure, also a node-based project, same RALF loop, same prompt, same everything. And all those slices here are 90% built just using AI. And you see here, these are quite a lot of slices. See that? It's a lot of slices and they are just here, one slice after the other. And if you look into those slices, they are exactly like this defined in the event model. So all those slices behave like very tiny modules or even microservices. They are standalone. They don't have any dependencies between each other besides the events. The events is the only thing that defines the contract between those slices, but everything else is completely independent. And this is why you can just keep them here. and all those slices and every slice is a very tiny business capability yeah christian another question yes a couple of questions normally there's this a learning record and the decision record in the ralph loop but i guess you don't need that too much uh what i what i do is yeah that's also a good point thanks for mentioning that so what i do is what i have is um there is the progress.txt file we can also it's also here you can look at it's called the build log here now you see basically what happened in each iteration so ralph of course logs what what did i do and also what did i learn and what i do is and i use this progress.txt after each loop and i record the learnings in the agents.md so here for example these are the learnings that ralph had now let's make this a little bit bigger oh this is a fresh project great yeah it creates the context events because there were no events there some learnings about assert not empty great state for simple create commands can be empty okay npm install require before npm run build great nothing special but those are learnings and these learnings move to the agents.md because then in the next iteration it knows this this this is gain knowledge over each iteration so the progress.txt is basically the working file you have all the everything that happens in an iteration in this file and if you're done with this all the learnings get compressed and into the agents md and then you basically your agent gets smarter each iteration that's what happens but what do you gain from i mean if you use static code analysis it would just take one iteration right then it will do it perfectly immediately what what do you mean if you will use a static code generator that just merge the parameters into the template yes of course so typically i have static code generators for this this was just to show um because sure because you have learnings in each iteration there is typically one or two learnings but the longer you work the smaller they get so in the beginning you have those those very basic learnings that you see here but later you just have okay in this special case if if this is a uuid and then the event model is not a uuid this is how we how we need to do it and it's really amazing how well those agents learn it's really crazy to see that they really understand what happens and they really really learn it's really great to see that and now we see only two slices um where mark has planned it's done uh iteration is over yes then Can you explain what was given to the AI agent? So how do you give it the information of the slices from the middle board? Oh yeah. And do you have other ID files with prompt parts that are used? So what is used to initialize the live loop? Yeah, yeah. Great questions. So let's quickly go through the structure here, what is used here. So if you look at the index.json, there is just, there is a folder defined here. The folder defines, okay, where is the slice definition? Because here, this is not the slice definition. This is just your work item. The slice definition is in, there's a .slices folder. And in the .slices folder, there is the real slice.json. And this is where... where everything in the slice is defined basically you have the command you have all the fields you have the types everything is here including the specifications so if you look at the uh what is it it's this one somewhere here is the specifications and here's the specification or you can only add three items and this is exactly what we defined in the event model and this is the real input for the agent so the agent picks up this and uses this together with the skills defined to build this slice this is enough you only need this that's basically that's your spec the spec plus the skills is enough to build the slice typically including the business logic so even even if you have more complex business logic that typically works very very well of course you need to review that but um oftentimes it's just it just works it's almost magical so you ask also about the md files so what md files do i have in my projects of course we have um the so let's start with the cloud md cloud md just gives the the basic assumptions okay this is what we use in the project this is how it's structured and stuff like that development guidelines that's in the in the cloud.md then we have the agents.md here is really these are the aggregated learnings overall iterations everything is in here so you see event management stuff like that most of this is just the result of iterations so i don't maintain this really manually this is all ai generated and typically the result of learnings and you see there's a lot of information in here what else do we have we have the prompt MD, that's just a prompt. So you see here, currently my RALF loop has 17 tasks that needs to be done. But yeah, that's basically it. So there isn't really more than that. And of course, the RALF is HA, which is the script that I run. That's basically what I do. So in the Agents MD, AI records its learning. So that is AI generated. Yes. The CloudMD and the PromptMD are manually implemented. Yes, they are static, they don't change typically, but the agent MD changes with each iteration. And so common gotchas, all you see here, that's all Cloud generated. I don't do this manually. Okay, and you said that the tracing that's manually generated is the base for the code generation that new claw needs to understand the neural json and is able to interpret it yes so it's basically that is encoded in the in the in the skill files and the skills is just defined okay what does a skill what does a slice look like what is the input and this is enough to interpret the json exactly so you have a skill md um to interrupt the json more or less so the the skill files just describe what a slice looks like so it describes this is a command this is what a command looks like and stuff like that and that that's enough so i there is no specific information here how to interpret the json because it's clear from the context you don't you don't need any special handling it's just just clear how to handle that But that are the instructions for the AI to interrupt the MiroJSON. There are no special instructions for the MiroJSON. It's just instructions how to build a slice, and the JSON is just the input. There are special instructions because it's very clear from the context, typically. OK, thank you. So any more questions about this? Martin, if I wanted to run it with Axon framework, I just need to modify the cloud.md, is that correct? Oh, I have a setup for Axon as well. So I use this a lot with Axon on the JVM, that works, that is the very same thing. Okay. Different skill files, but the cloud.md, the Ralph.sh, very same, absolutely the same. Okay, and I can use cloud or I can use GitHub Copilot. does it really matter well this is a this is um specialized for claw because you have the skill files and everything but of course you can adjust that for for copilot of course thank you so um time is already up so let me just quickly um tell you what will happen now so this also works for your team if you want to use this in your team you can try this i can help you with this if you want to try this with your team just contact me i'm very happy to help and I will send to you, since you are registered for the webinar, you will get the link to the repository. This is the repository. You can also jump to it right here. There you find the RalphSH. There you find everything. This is the link to the Miro board. You can access this. So you can really start to play around with this literally today if you want. You can just clone this repository, run RalphSH, and it will start to build. If you have Claude installed locally, you don't need more than this. Any more questions? about that before we close the webinar there was a lot of information um hope you took something out of it yes christoph oh yes how do you stop uh clove from using all your tokens oh you you can't that's why you have the iterations so you define 10 iterations um and after 10 iterations it typically stops and then you can either restart or um yeah You need to define how you do that. You could also, I think you can also ask for the available tokens, but I just, I run 10 iterations and after 10 iterations it stops. Thank you. Yeah, now the other Christoph. Hi Martin, thank you for the introduction of the rough loop. I just was wondering if you also played around with spec driven development? Yeah, that's the very same thing. That's the very same thing. This is spec-driven development. The event model is your spec. I mean, you could also use something like Kiro or something, but that's the very same thing. So my tool of choice is just event modeling because it works so well. You could use any other spec, of course, as well. It doesn't make any difference. Okay, thanks. Anything else? Well, if not, so hopefully that was well worth your time. that's always important thanks for joining um and please play around with the ralph loop it's really it's a lot of fun and it's really a productive tool all right then thanks for joining and see you next time
⚙️ Pipeline jobs
| Stage | Status | Att. | Updated | Error |
|---|---|---|---|---|
| download | done | 1/3 | 2026-07-20 15:05:08 | |
| transcribe | done | 1/3 | 2026-07-20 15:05:45 | |
| summarize | done | 1/3 | 2026-07-20 15:06:18 | |
| embed | done | 1/3 | 2026-07-20 15:06:20 |
📄 Описание YouTube
Показать
In this 1-hour Webinar, Martin Dilger demonstrates how to design and build a production-ready event-sourced Node.js application using Event Modeling, AI code generation, and the Ralph-Loop technique. Learn how to: Break down a system into functional building blocks (slices) that are perfect for AI integration Model business rules clearly using Given-When-Then Generate 80% of your code structure without spending AI tokens Use Ralph-Loop to iteratively improve AI agents while preventing context overload Ensure information completeness to avoid wrong assumptions and costly rework Collaborate with business experts to capture real requirements Translate a fully specified Event Model into frontend and backend code Apply real-world Event Models at scale, not just small examples Tech Stack Covered: Node.js runtime Express.js API layer React frontend MIT Event Sourcing framework (Node.js) Martin also shares lessons from his book "Understanding Event Sourcing", showing how the same patterns from Java/Kotlin/Spring projects apply to Node.js. Discover how Event Modeling structures your system for AI, reduces coupling, and makes feature development faster and safer. Highlights: From simple requirements to a fully specified system Real examples of large-scale Event Models AI-assisted code generation combined with static scaffolding Step-by-step screen, command, event, and read model design Practical tips for avoiding feature explosion and architectural decay 💡 Whether you’re a developer, architect, or AI enthusiast, this workshop shows how to combine Event Modeling, Event Sourcing, and AI agents to build maintainable and scalable systems. ⏱️ Duration: 1h 5min 31s