Archive

Archive for the ‘architecture’ Category

arquitecturas escalables e invisibles

June 14th, 2016 No comments

AWS Lambda, Azure Functions, Google Cloud Functions, OpenWhisk from IBM … el mundo “serverless” se nos viene encima con todo el furor de un hype en celo … la opción de ejecutar código sin provisionar nada, meras “funciones” expuestas en internet. ¿Va a seguir el servidor de aplicaciones el mismo rumbo a la obsolescencia que el famoso mando intermedio? ¿Irá detrás el servidor web? No en vano el technology radar de abril del 2016 de ThoughtWorks dice que precaución con el servidor de aplicaciones (“hold“, como lo clasifican ellos) como pieza clave del ecosistema. Como siempre, depende y las cosas y las organizaciones varían mucho en su adopción o su pereza (los “laggards”). Pensemos también, por otra parte, en la extensión de las beneficiosas consecuencias – a priori – para temas de seguridad, patching, gestión, etc (¿malware si no hay servidor?). Otra vuelta de tuerca en la idea de correr cosas virtuales sobre cosas virtuales sobre cosas virtuales (“it´s virtual machines all the way down”).

A pesar de que la idea es vendida como si se pudieran simplemente “colgar” funciones independientes en la nube – ¿y en realidad no deja de ser un servicio web justo eso? – al final los proveedores lo que hacen es envolver esas funciones en una API gateway y exponerlas para que los clientes las llamen mediante el popular REST. Esto se apoya en que tiene que haber un entorno de ejecución, un contenedor con la máquina virtual (me refiero a la maquina virtual de Java por ejemplo, no a una maquina virtual en su otra concepción). La ventaja es tener ahora algo más ligero que un OS para poder correr una VM para poder correr una lambda, optando por apoyarse en un contenedor que tiene lo justo y necesario, o corriendo directamente sobre el hypervisor.

Citando de la pagina de AWS Lambda “the core components are Lambda functions and event sources. An event source is the AWS service or custom application that publishes events, and a Lambda function is the custom code that processes the events.” Esto me sugiere arquitecturas reactivas, observables, incluso eliminar ese viejo ESB… escenarios de integración y transformación de datos. Sugiere también sistemas difíciles de depurar, difíciles de entender y de razonar sobre ellos, como contrapartida. Sugiere programación funcional y construir sistemas enteros en este paradigma, combinándolo con un uso juicioso de CDNs. Desde luego, potencialmente puede significar muchos cambios a nivel de arquitectura de soluciones. Hay gente construyendo sistemas enteros con piezas (¿de lego?) como Auth0, Firebase, API Gateway, Lambda, SQS, S3, CloudSearch, Elastic Transcoder, etc.


robust profits

Evidentemente, no es que los servidores realmente desparezcan, sino que más bien desaparecen como preocupacion del desarrollador: problemas como despliegues, escalado, configuracion e incluso el propio sistema operativo se nublan en el olvido, mientras nos centramos en servicios y plataformas elasticas de computacion. La teoria dice que ahora es aun más facil construir sistemas complejos que pueden crecer, escalar, evolucionar a medida – el clásico sales pitch, que ya sabemos que no es tan sencillo ni tan bonito todo.

Para saber más:

Comparativa entre AWS Lambda y Azure Functions

ThoughtWorks sobre Serverless Architecture

What is serverless

entrada sobre Serverless en CloudAcademy

reflexiones sobre el rol de arquitecto…

March 14th, 2016 No comments

Entre las “recriminaciones” que son cliché habitual acerca de los arquitectos y su rol, además del síndrome de la torre de marfil, es habitual oír quejas acerca de esa tendencia entre a querer abandonar los proyectos una vez que la parte digamos “interesante” de los mismos está finalizada o a punto de finalizar (¿instinto de supervivencia? 😉 ). Es decir, que una vez que se ha planificado la arquitectura, se han agotado todos las excusas para asistir a infinitas reuniones y desayunos de trabajo, los viajes y se han planificado las ejecuciones y todo parece perfecto sobre el papel, lo famosos arquitectos desaparecen.  En realidad, no sé si realmente existen estas figuras mitológicas tal cual hoy día, tal vez antaño, pero yo no las he visto, aunque si he visto gente con los pies muy lejos de la tierra en todo tipo de posiciones.  No creo que sea solo culpa del ser humano individual (si bien es muy cierto eso de que “everyone wants to design, nobody wants to maintain”…), sino también de las organizaciones, que al fin y al cabo son construcciones colectivas.

 

Hay otra forma de ver las cosas: el arquitecto debería ser el propietario “end-to-end” de la solución.  Es más, este rol ni siquiera es algo fijo sino que debería cambiar o evolucionar en consonancia con las distintas fases del ciclo de vida del proyecto.  Creo que esto no se reivindica o se resalta suficientemente, tanto para unos como para otros. Teóricamente, nadie mejor que el arquitecto debería conocer la solución mejor.  A nada que uno haya estado en esta industria suficiente tiempo, se dará cuenta que poco o nada tienen que ver el papel y esos archivos .vsx iniciales con la implementación real del sistema al final de la “larga marcha”, y lo que parece muy completo y casi “perfecto” en los powerpoints – que lo soportan todo -, no tiene nada que ver con la realidad ( que básicamente es lo mismo que les suele pasar a esos ejercicios de wishful thinking que son los Gantt, especialmente en el caso flagrante de aquellos creados antes de tener claros los requisitos, ni de haber tirado una línea de código, los Gantt “promesa política” que los llamo yo, pero ese es tema para otro post ).  Al igual que ocurre con los dichosos Gantt que tanto daño han causado, es fútil pretender que se puedan conocer de antemano todas las circunstancias cambiantes, errores, problemas, asunciones y premisas que cambian y todo tipo de factores imposibles de anticipar, porque al final se trata de sistemas “vivos” (creo que los matices en “live” lo expresan mejor).

 

Debido a todo esto, es imprescindible que el arquitecto continúe en el proyecto – al menos en un rol de supervisión y liderazgo técnico dando soporte al equipo y a negocio -, hasta incluso durante la fase de entrega, donde sigue teniendo un rol importante.  No basta con ser un arquitecto en su torre de marfil, y se debe revalidar el papel del “coding architect” que conoce también la implementación de su solución y los requisitos de infraestructura, y como dar soporte a los requisitos no funcionales elicitados.  Ciertamente, hoy día se ha desgranado o especializado tanto el papel del arquitecto que el termino corre grave peligro de no significar nada, o de significar cualquier cosa, y dependiendo de la empresa tenemos simultáneamente cualquier combinación de data architect, business architect, integration architect, Infrastructure architect, solutions architect, Enterprise architect, information architect, delivery architect, UX architect, etc. etc.)

Data science


Al hilo de esto lo cierto es que tal vez el rol del arquitecto sea tan difícil de definir porque las habilidades y tareas del rol van cambiando según el proyecto va agotando fases en su imparable carrera hacia el <sarcasmo>más fulgurante éxito, directo al cuadrante mágico</sarcasmo>. Por lo que me toca más cercano, es fácil ver como el solutions architect debe irse convirtiendo en un delivery architect (podríamos decir arquitectos de entrega o algo así, pero queda fatal). Esto al final, no es más que insistir en el principio de responsabilidad (responsibility and accountability) y de propiedad (ownership –  a veces los vocablos ingleses parecen transmitir mejor la carga semántica).  Al principio será más el responsable de entender bien los requisitos, coordinarse con los stakeholders de negocio (son diferentes skills, como vemos, tanto técnicos como sociales) y entender los limites tecnicos, presupuestarios, manejar expectativas, el entorno político y cultural, y dar lo que parezca la mejor opción, a su juicio y con los datos disponibles.  Sin embargo, nada – y nunca mejor dicho lo de “nada” – acaba con la entrega de un montón de documentos, de entregables definidos por nuestro framework de arquitectura preferido.

 

El aspecto clave durante la vida del proyecto es la gestión técnica, alejándose de esos arquitectos extremófilos acostumbrados al aire enrarecido de la sala de juntas, donde de nuevo tenemos capacidades muy diversas que aportar: gestión de stakeholders y/o grupos de interés, gestión de deuda y riesgos técnicos, calidad, metodologías, gestión de equipos, “fit-for-purpose”, gobernanza y, sobre todo, asegurarse de que la solución no se desvía del alineamiento con la arquitectura empresarial y los objetivos tácticos o estratégicos a los que debe su existencia.

 

Aquí es donde probablemente la línea entre Solutions Architect y Delivery Manager se solapa mucho, y podemos hablar de otro rol más, el de Delivery Architect, y es que el delivery manager raramente tendrá el mismo conocimiento que el arquitecto de una solución específica, ya que éste es el propietario de la solución completa, por tanto es de suponer que el arquitecto sería el que tiene la mejor y más completa visión y el conocimiento sin el cual, el Delivery Manager tendría muy difícil ser capaz de cumplir con sus responsabilidades correctamente.  A menudo el factor decisivo en el éxito o no de un proyecto será la colaboración eficiente entre el Delivery Manager y el arquitecto, no la calidad sobre el papel, no la belleza del diseño de la solución en unos cuantos visio o UMLs. El arquitecto debe por tanto ayudar en todo al Delivery Manager para que se tomen las mejores decisiones. En esto el arquitecto pasa a ser un delivery architect. Su rol va – y debe hacerlo – mutando según evoluciona el proyecto. Esta figura que llamamos el delivery architect también debe de no perder de vista el foco en los requisitos no funcionales. No solo se trata de definirlos – que también – sino de asegurarse que el Sistema o la solución propuestas y desarrolladas se adhieren a dichos requisitos. No olvidemos que al final se trata de que la arquitectura de soluciones realizada sea operable y efectiva desde el punto de vista del coste y de las estrategias definidas a nivel empresarial.

A riesgo de sonar muy pomposo, cierro con una cita de un libro que no he leído

Se audaz y astuto en tus planes, firme y perseverante en su ejecución, decidido en encontrar su glorioso final.

Carl von Clausewitz, De la guerra 

 

 

More stuff on microservices, this time for the .net world

July 15th, 2015 No comments

What factors are important for microservices? (a.k.a. fine-grained SOA). It’s said that Node.js is an excellent fit for a microservices approach – which lends itself very well to the fashionable container approach – as it has the following:

  • Excellent package system (npm)
  • Minimal effort to publish new packages (package.json)
  • Node.js itself encourages lightweight, narrow-focus services, not big monolith-ish services
  • Designed to be async I/O in order to achieve better scalability
  • End-to-end javascript stack

This is all very true, and we can add ease of “containerization” of those services.  What about those of us who work in the .net world? For years, the perception that the .net world was somewhat behind in certain aspects, such as DDD adoption (or the blissful ignorance of it), microservices, containers (which are coming soon in windows) and so on. However, I think the tooling is improving a lot this year and sweeping changes are coming to the platform with the advent of .net core, the new runtimes, etc. Well, we can have all of this, although we might have to make more of a conscious effort to steer our development practices and inertia towards a more similar approach.

  • We have a good package system, nuget, and we also have chocolatey (check out the difference). You can even implement your own nuget feed.
  • So that means you could bundle certain things in packages (for example, implement cross-layer concerns, AOP stuff, etc. in nuget packages) and then add them to your nimbler solutions
  • The new VS2015 brings great improvements to the web project idea, doing away with the classic solution approach we are so familiar with and taking the .net developer to the folder-based solution structure, as we are used to see in many other languages. With this, there comes semantic versioning, and json files for handling dependencies, the ability to bring grunt.js and gulp.js on board, introduce better minification and uglification into the build process, and so on, so in this sense the .net developer has been brought into the same arena as developers in the .js world.
  • Use Web API or REST-ful traditional WCF web services – if you have such legacy services, they can be restified easily (pdf)-, or NancyFX, or ServiceStack
  • You can have async as well, of course

So it’s perfectly possible to get the same approach (except the full-stack thing). You can dockerize too those services, if you want. This way you achieve this same “component”-oriented architecture. Don’t miss the “Docker for .net developers” Channel 9 (by Dan Fernandez) series if you want to gain a clearer picture of how Docker and .net applications fit together.Naturally, you get the same drawbacks:

  • Deployments get more complicated. No need to argue that a monolithic application could be easier to deploy, although often those deployments are riddled with fears as well. At the same time though, error surface in deployments gets reduced, or more scoped, in the sense that if only one service is causing errors, at least you know where to look, and scope is not as big as in a monolithic application.
  • As deployments get more complicated, you certainly need to automate testing and deployment, so depending on your current practices, or skill sets, this might be possible, or downright impossible if a previous effort to bring operations up to date is not done first. So, many companies will find themselves not to be in the right position for this point and the previous one. Especially if there is no culture of DevOps.
  • Operations get more complex, hosting, managing, lifecycles, monitoring more systems, more processes, more logs (integrated views needed here) etc.
  • Need to consider messaging patterns, need to consider how to handle transactions, if at all, or compensating them, need to consider how to test processes spanning several services that interact together.
  • Need to consider sharding and partitioning your database. After all, what use is deploying redundant copies of your services if they’re all going to be talking to the same database?  You get a potential bottleneck and a dangerous weakest link in your system. If using databases such as mongoDB, you need to have replica sets, or similar mechanisms in other systems.

Significant challenges lie ahead. Probably it’s safe to assume that not everything is quite mature in this confluence space between microservices, containers, and the usual, and not so easy, concerns of scaling, replication, hosting, clustering, service discovery inside containers, resource and performance (cpu, ram, disk etc) and so on and so forth. Kubernetes is something to watch closely in the near future, now that we can run on Linux too.  Containers can have their own security issues, especially if you download images you’re not 100% sure about their provenance.Dealing with failed services / containers.  I think that bringing some of the strategies the actor model proposes in the face of errors could be interesting. After all, in a way one can imagine containers to be somewhat like actors, they’re cheap, lightweight (actors are better in this sense), easy to start or to kill which brings me to the point where maybe considering a pure actor model (akka.net -ported from classic Akka- or even Microsoft Orleans) could be a better option. You can have millions of them, ready to work for you behind your API gateways. I think that could be a nice idea, or at least it looks very nice on paper. Surely it is not so easy to implement as it is to dream it.  Certainly we’re in for a big sea change 🙂

simple request weight

June 12th, 2015 No comments

This is just a sketch of an idea for all manner of web-based applications, LOB applications or otherwise. The idea is that requests to the server should provide or be enriched with some sort of metadata that would enable the server to inspect a given request and decide on the configured importance of that request. This could either be done from the client side of the application, which then should have some modicum of business knowledge so that all requests to the server are wrapped or enriched with some metadata describing a degree of priority, for example, or some sort of indicator.

This is not very new, as that wrapping might reming of old-style SOAP enveloping. Also the idea of some sort of metada or cataloguing of requests is similar to what you find implemented in certain frameworks, for example, actor frameworks like Akka.NET have a similar mechanism in virtue of which, system messages can jump to the top of the queue for priority processing. If we want to keep the client side free from these troubles and the necessary knowledge, other strategies can be followed. This wrapping or enriching of requests could be outsourced to some dispatcher component that centralizes and takes care of that task.

Obviously you need that this extra step does not become some sort of bottleneck when processing a lot of requests. Given that the task is well-scoped and stateless, it is easy to think of this as a fast web service, even a tcp.net windows service – if that suits your application typology -, or some cloud-based job, that could keep it’s necessary configuration or rules in a small memory cache, and even, with some extra work, be able to be reconfigured while live. In an even simpler way, we could just create some configuration database so that the server side can actually look at a request and then decide. In the simplest scenario, the URL could already give a lot of information for decision, especially if you have a well-crafted web api design. For example, you could choose to server first people who are using v2 of your api (www.mygreatcompany/api/v2/product/123) instead of those still using the v1, or you could inspect metadata to understand if your user is a paying platinum member instead of a bronze free account.

Or you could discrimate by locale. If you have 0 presence in China, and you suddenly get a lot of traffic from China, maybe you don’t want to pay that much attention to that (leaving other security concerns aside here). Similarly, in some applications you could have “system” messages that you want to have priority, for example, refreshing a piece of data held in cache immediately. To make this into a configurable, reusable mechanism probably a good way is to configure a simple map or hashtable of identifiers and assigned weights, something along the lines of this one below, even combining different aspects (URL inspection, user metadata, etc) of inspection to better decide on the business weight of a request:

Such a structure would be easy to customize in each application according to needs, so that each could roll out its own requests analyzer according to business needs. This strategy could also be used in conjunction with other patterns, such as an azure priority queue, to which the most important messages could be routed to. I am sure there are holes in this and plenty of room for improvement, but I think the idea could be interesting in many scenarios, and in some of them a simplified approach can do. Overly complicated systems are also expensive, so sometimes, some duct tape can do, at least as an spike, and then if the idea proves good, then learn and refine, of course.

Categories: architecture Tags:

the actor model

November 6th, 2014 No comments

Now that the reactive model is becoming the hot new thing in some circles – although still far from becoming a “popular” thing among average developers -, it’s a good thing to get more familiar with the actor model. Quoting from wikipedia,

The actor model in  computer science is a mathematical model of concurrent computation that treats “actors” as the universal primitives of concurrent computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received

Not that this is a new thing really, since the actor model comes from 1973, but many such innovations often take years and years to gain mainstream adaption (think for example lambdas or garbage collection, who seem like relatively new and welcome additions to main programming languages, but that were in Lisp way before).Some references to know more about the actor model then

There are also some interesting books in the market about the actor model, but these links are already a good introduction to this very interesting topic. The entry from wikipedia itself also offers a plethora of additional references.

Some frameworks, most notably Akka in the JVM / Scala world, and its .net porting, Akka.net, as well as Microsoft’s own Orleans framework are the best known tools in the industry.

Categories: architecture Tags: