Saturday 18 November 2017

Zeromq Trading System


Gran trabajo Im tratando de ejecutar el ejemplo con la biblioteca precompilada sin embargo estoy recibiendo el error de carga de DLL: 16:44:55 zmq EURUSD, Diario: cargado con éxito 16:44:55 zmq EURUSD, Diario: inicializado 16:44:55 zmq EURUSD , Daily: no se puede cargar la biblioteca zmqbind. dll (250 caracteres) error de classlinkator 126) 16:44:55 zmq EURUSD, Diario: experto parado 16:44:55 zmq EURUSD, Diario: desinitializado 16:44:55 zmq EURUSD, Diario: Cualquier razón por la que estoy recibiendo esto tengo habilitar las llamadas DLL en las opciones y otros scripts pueden cargar desde la carpeta de expertos / librerías. Im en Windows XP de 32 bits y metatrader 4 de MIG construir 229. Supongo que tiene zmqbind. dll en expertos / bibliotecas También tendrá que colocar libzmq. dll en c: / windows / system32 (o dondequiera que todos los dlls otro sistema son). Alternativamente, puede establecer alguna variable de entorno (dontn recordar cuál) que permitirá a las ventanas encontrar libzmq. dll. Libzmq. dll es la biblioteca zeromq precompilada para 32 bits. Mientras que metatrader será capaz de encontrar y cargar zmqbind. dll, desde allí en el cargador de Windows dll se hace cargo, y no sabe que es debe buscar en los expertos / bibliotecas para encontrar libzmq. dll. En un par de días voy a estar lanzando una versión más completa que incluirá sondeo en un socket zeromq con un tiempo de espera, múltiples mensajes recibir / enviar, publicar zócalos, zócalos inproc y zócalos de tubería. Tenga en cuenta que podría potencialmente encuesta también en un socket regular, pero no tengo el código para probar que, por lo que no hará enlaces para esa parte. Por supuesto, todos mis archivos están en su lugar sin embargo estoy perdiendo algunos. He dirigido el Dependency Walker y parece que faltan pocos archivos (vea la imagen de abajo). ¿Puede por favor agregarlos a la distribución parece que le falta microsoft visual runtime. Me olvidé de mencionar eso. Personalmente, tengo microsoft visual studio 2008 express instalado, por lo que havent probado hacerlo de esta manera. Descargar desde aquí En cuanto al error de configuración lado a lado, no he oído hablar de esto. Lo busqué y parece ser un problema con algunos microsoft parche - si uno no tiene Visual Studio Express instalado, que happends. Corro microsoft en virtualbox y no sé si he actualizado mi xp para solucionar este problema. Si la descarga del tiempo de ejecución visual no funciona, podría tener que recompilar todo después de la actualización. Tenga en cuenta que funciona en mi xp. MQL4 Comentarios 2011.02.11 13:45 2011.02.11 13:45:29 ¿Podría, por favor, publicar la versión sin depuración de su biblioteca Creo que esto resolverá la mayoría de los problemas descritos en los comentarios. Y creo que será útil para todos. ¿Podría, por favor, publicar la versión no depuración de su biblioteca creo que esto resolverá la mayoría de los problemas descritos en los comentarios. Y creo que será útil para todos. No tengo ni idea si la descarga del archivo descrito en la publicación anterior funciona. Es definitivamente necesario. No debería importar si es depurar o ejecutar dll, excepto quizás una pequeña diferencia en velocidad. ¿Está teniendo problemas similares? Tenga en cuenta que también incluí el script cmake para construir la versión de Windows, por lo que podría construirlo también. Por supuesto, usted necesita los archivos lib apropiados para zeromq. Tenga en cuenta que la depuración de alguien elses problemas de forma remota requiere pequeños pasos, por lo que no debe ponerse fuera si se necesita un montón de comentarios para conseguir trabajo. No dude en hacer preguntas. Tenga en cuenta que los ejemplos funcionan para mí, así que no tengo ni idea. Pero también tengo Visual Studio 2008 instalado. También note que no compruebo generalmente esto más de una vez por día, así que si usted fija algo espera que tome en el mejor un día en respuesta. Así que haga la pregunta countWARNING: Este texto está obsoleto y se refiere a una versión antigua de MQ. Permanece aquí para el interés histórico. NO UTILICE ESTO PARA APRENDER MQ. Introducción Como MQ se destina principalmente a las empresas de comercio de acciones de poder, hemos creado una aplicación de ejemplo que simula el funcionamiento interno de una bolsa de valores. El objetivo principal de este ejemplo es mostrar cómo MQ perfroms en el mundo real-como escenario. Diseño El siguiente diagrama muestra la arquitectura de la aplicación: El componente Gateway debe recibir órdenes de los comerciantes a través de la red (utilizando el protocolo FIX o un protocolo propietario específico) y enviar respuestas a los comerciantes. Sin embargo, como la aplicación de ejemplo tiene la intención de mostrar cuáles son los posibles throughputs / latencias de tal sistema, gateway genera órdenes al azar en lugar de recibirlas de los comerciantes. Al iniciar la puerta de enlace, puede especificar el número de pedidos por segundo que se generarán. Unidad de coincidencia contiene el núcleo de la lógica de la bolsa de negocios. Hace coincidir las órdenes entre sí y produce transacciones y cotizaciones. Nuestra implementación es minimalista, basada en el algoritmo de coincidencia de tiempo / precio (la implementación del algoritmo pro rata se deja como un ejercicio para el lector). Aún así, el algoritmo tiene complejidad de O (1) y está muy optimizado. Hemos visto que procesa unos 18 millones de pedidos por segundo. El componente Estadísticas recibe información de rendimiento generada por la puerta de enlace y el motor coincidente y lo muestra en forma legible por humanos. Para facilitar la lectura de las estadísticas, en el ejemplo se incluye una herramienta gráfica sencilla. Rendimiento La siguiente captura de pantalla muestra ejemplos de rendimiento en dos cajas de 8 núcleos (3GHz) de gama alta, cada una de las cuales tiene 2 NIC 1GbE dedicadas. Tenga en cuenta que si lo ejecuta en el hardware no especificado y / o sin ajustar, puede seguir siendo bastante rápido, sin embargo, youll experiencia menor throughputs de mensajes y más picos de latencia. Si usted fija la tarifa del mensaje demasiado alta usted puede incluso experimentar el fracaso del gatway pues el componente del ticker usado para enviar órdenes en la tarifa estable no será capaz de guardar paso. La línea amarilla muestra latencia de ida y vuelta, es decir, cuánto tiempo tardó en pasar la orden desde la puerta de enlace al motor correspondiente, procesarlo y devolver la confirmación de la orden a la pasarela. En nuestra prueba de latencia fluctúa alrededor de 200 microsegundos promedio. La línea de rendimiento inferior (900.000 mensajes / segundo) es la tasa de órdenes que se pasan desde la puerta de enlace al motor de coincidencia. La línea de rendimiento superior (2.300.000 mensajes / segundo) es la tasa de confirmaciones de pedidos, transacciones y cotizaciones de acciones pasadas del motor de concordancia a la pasarela. En total, hemos visto aproximadamente 3.200.000 mensajes por segundo pasando por la red. Construirlo Para construir el ejemplo use --with-exchange option con configure: Para poder ejecutar la herramienta de graficación usted tiene que tener instalado Perl-Tk (empaquetado como perl-tk en Debian) así como Tk :: Graph de CPAN . Ejecutarlo Por ejemplo, tenemos la siguiente topología de red para ejecutar el ejemplo. Las casillas representan máquinas individuales, las flechas representan cables físicos entre interfaces de red individuales (marcadas por sus respectivas direcciones IP): Hay tres casillas (test01, test02 y test03) conectadas a la red conmutada con direcciones IP respectivas de 192.168.0.1, 192.168.0.2 Y 192.168.0.3. Además hay dos conexiones directas entre test02 y test03. Una conexión conecta la interfaz de red 10.0.0.1 en test02 con la interfaz de red 10.0.0.2 en test03. Otro conecta la interfaz de red 10.1.0.1 en test02 con la interfaz de red 10.1.0.2 en test03. Bien ejecutado zmqserver y el componente estadístico en test01, el motor de coincidencia en test02 y la pasarela en test03. Utilice bien una de las conexiones directas entre test02 y test03 para pasar las órdenes de gatway al motor de concordancia y el otro para pasar las confirmaciones, los oficios y las cotizaciones del motor de concordancia a la pasarela. Primero, inicie zmqserver en test01: Luego inicie el componente estadístico en test01. Los parámetros son el cuadro donde se ejecuta zmqserver y la interfaz de red para recibir información estadística sobre: ​​Alternativamente, puede canalizar los datos estadísticos a la herramienta de representación gráfica: Ahora inicie el motor correspondiente. Suministre el nombre de host de zmqserver, la interfaz para recibir mensajes y la interfaz para enviar mensajes como parámetros: Finalmente, ejecute el gatway. Suministre la ubicación de zmqserver y el número de órdenes a enviar por segundo como parámetros: Conclusión El ejemplo de Exchange le permite probar el rendimiento de MQ en un escenario de tipo real. Sin embargo, conseguir una latencia estable a altas velocidades de transmisión es un asunto difícil dependiendo de la optimización general de su hardware, sistema operativo, entorno de ejecución, etc. Si se toma en serio las pruebas de rendimiento, póngase en contacto con nosotros para ayudarle con la tarea. Escrito: 1218019882Y. m.e Revisado: 1286694428Y. m.e Si esta página le resultó útil, por favor puntúela para que otros la encuentren. Consulte tambiénZeroMQ OslashMQ es un sistema de mensajería, o middleware orientado a mensajes, si lo desea. Se utiliza en entornos tan diversos como servicios financieros, desarrollo de juegos, sistemas embebidos, investigación académica y aeroespacial. Los sistemas de mensajería funcionan básicamente como mensajería instantánea para aplicaciones. Una aplicación decide comunicar un evento a otra aplicación (o múltiples aplicaciones), reúne los datos a enviar, pulsa el botón de envío y allí gomdashthe el sistema de mensajería se encarga del resto. A diferencia de la mensajería instantánea, sin embargo, los sistemas de mensajería no tienen interfaz gráfica de usuario y no asumen ningún ser humano en los extremos capaces de intervención inteligente cuando algo sale mal. Por lo tanto, los sistemas de mensajería deben ser tolerantes a fallos y mucho más rápidos que los mensajes instantáneos comunes. OslashMQ fue originalmente concebido como un sistema de mensajería ultra-rápido para el comercio de acciones y por lo que el foco estaba en la optimización extrema. El primer año del proyecto se dedicó a diseñar una metodología de benchmarking y tratar de definir una arquitectura que fuera lo más eficiente posible. Posteriormente, aproximadamente en el segundo año de desarrollo, el enfoque se centró en proporcionar un sistema genérico para construir aplicaciones distribuidas y soportar patrones de mensajería arbitrarios, varios mecanismos de transporte, enlaces arbitrarios de idiomas, etc. Durante el tercer año el enfoque se centró principalmente en mejorar la usabilidad Y aplanar la curva de aprendizaje. Hemos adoptado el BSD Sockets API, hemos intentado limpiar la semántica de los patrones de mensajería individuales, y así sucesivamente. Con suerte, este capítulo le dará una idea de cómo los tres objetivos anteriores se tradujeron en la arquitectura interna de OslashMQ, y proporcionar algunos consejos para aquellos que están luchando con los mismos problemas. Desde su tercer año OslashMQ ha superado su código base hay una iniciativa para estandarizar los protocolos de cable que utiliza, y una implementación experimental de un sistema de mensajería OslashMQ-como dentro del kernel de Linux, etc Estos temas no están cubiertos en este libro. Sin embargo, puede consultar los recursos en línea para obtener más detalles: www.250bpm / concepts. Groups. google/group/sp-discuss-group. Y www.250bpm / hits. 24.1. Aplicación contra biblioteca OslashMQ es una biblioteca, no un servidor de mensajería. Nos tomó varios años trabajando en el protocolo AMQP, un intento de la industria financiera para estandarizar el protocolo de alambre para mensajería de negocios, escribir una implementación de referencia para él y participar en varios proyectos a gran escala basados ​​en tecnología de mensajería para darse cuenta de que theres algo malo con el clásico cliente / Servidor de servidor de mensajería inteligente (intermediario) y clientes de mensajería tonto. Nuestra principal preocupación en el momento era con el rendimiento: Si theres un servidor en el medio, cada mensaje tiene que pasar la red dos veces (desde el remitente al corredor y del corredor al receptor) induciendo una pena en términos de latencia tanto Y el rendimiento. Por otra parte, si todos los mensajes se pasan a través del corredor, en algún momento su obligado a convertirse en el cuello de botella. Una preocupación secundaria estaba relacionada con los despliegues a gran escala: cuando el despliegue cruza los límites de la organización, el concepto de una autoridad central que gestiona todo el flujo de mensajes ya no se aplica. Ninguna empresa está dispuesta a ceder el control a un servidor en diferentes empresas hay secretos comerciales y hay responsabilidad legal. El resultado en la práctica es que hay un servidor de mensajería por empresa, con puentes escritos a mano para conectarlo a sistemas de mensajería en otras empresas. Todo el ecosistema está así muy fragmentado, y mantener un gran número de puentes para cada empresa involucrada no mejora la situación. Para resolver este problema, necesitamos una arquitectura totalmente distribuida, una arquitectura donde cada componente puede ser gobernado posiblemente por una diversa entidad del negocio. Dado que la unidad de administración en la arquitectura basada en servidor es el servidor, podemos resolver el problema instalando un servidor separado para cada componente. En tal caso, podemos optimizar aún más el diseño haciendo que el servidor y el componente compartan los mismos procesos. Lo que acabamos con es una biblioteca de mensajería. OslashMQ se inició cuando tuvimos una idea acerca de cómo hacer que el trabajo de mensajería sin un servidor central. Requirió convertir todo el concepto de mensajería al revés y reemplazar el modelo de un almacén centralizado autónomo de mensajes en el centro de la red con un punto final inteligente, una arquitectura de red estúpida basada en el principio extremo a extremo. La consecuencia técnica de esa decisión fue que OslashMQ, desde el principio, era una biblioteca, no una aplicación. Mientras tanto, hemos podido demostrar que esta arquitectura es tanto más eficiente (menor latencia, mayor rendimiento) y más flexible (su fácil de construir topologías complejas arbitrarias en lugar de estar atado al modelo clásico de hub-and-spoke). Una de las consecuencias no deseadas, sin embargo, fue que optar por el modelo de la biblioteca mejoró la usabilidad del producto. Una y otra vez los usuarios expresan su felicidad por el hecho de que no tienen que instalar y administrar un servidor de mensajería independiente. Resulta que no tener un servidor es una opción preferida, ya que reduce el coste operativo (no es necesario tener un administrador del servidor de mensajería) y mejora el tiempo de salida al mercado (no es necesario negociar la necesidad de ejecutar el servidor con el cliente, La dirección o el equipo de operaciones). La lección aprendida es que al iniciar un nuevo proyecto, debe optar por el diseño de la biblioteca si es posible. Su bastante fácil de crear una aplicación de una biblioteca invocándolo de un programa trivial sin embargo, es casi imposible crear una biblioteca de un ejecutable existente. Una biblioteca ofrece mucha más flexibilidad a los usuarios, al mismo tiempo que les ahorra esfuerzo administrativo no trivial. 24.2. Global State Las variables globales no juegan bien con las bibliotecas. Una biblioteca se puede cargar varias veces en el proceso, pero aún así theres sólo un solo conjunto de variables globales. La Figura 24.1 muestra una biblioteca OslashMQ que se está utilizando desde dos bibliotecas diferentes e independientes. La aplicación a continuación, utiliza ambas bibliotecas. Figura 24.1: OslashMQ siendo utilizado por diferentes bibliotecas Cuando se produce tal situación, ambas instancias de OslashMQ acceden a las mismas variables, dando como resultado condiciones de carrera, fallos extraños y comportamiento indefinido. Para evitar este problema, la biblioteca OslashMQ no tiene variables globales. En su lugar, un usuario de la biblioteca es responsable de crear explícitamente el estado global. El objeto que contiene el estado global se denomina contexto. Mientras desde el contexto de la perspectiva de los usuarios se parece más o menos a un grupo de hilos de trabajo, desde la perspectiva de OslashMQs es sólo un objeto para almacenar cualquier estado global que necesitamos. En la imagen de arriba, libA tendría su propio contexto y libB tendría su propio también. No habría manera de que uno de ellos rompiera o subvertrase al otro. La lección aquí es bastante obvia: no utilice el estado global en las bibliotecas. Si lo hace, es probable que la biblioteca se rompa cuando sucede que se instancia dos veces en el mismo proceso. 24.3. Rendimiento Cuando OslashMQ se inició, su objetivo principal era optimizar el rendimiento. El rendimiento de los sistemas de mensajería se expresa utilizando dos métricas: throughputmdash cuántos mensajes se pueden pasar durante un período de tiempo determinado y latencymdash cuánto tarda un mensaje en pasar de un extremo a otro. ¿Qué métrica debemos enfocarnos en cuál es la relación entre los dos? No es obvio Ejecutar la prueba, dividir el tiempo total de la prueba por el número de mensajes pasados ​​y lo que obtienes es latencia. Divida el número de mensajes por tiempo y lo que obtiene es throughput. En otras palabras, la latencia es el valor inverso del rendimiento. Trivial, right En lugar de empezar a codificar de inmediato pasamos algunas semanas investigando las métricas de rendimiento en detalle y nos enteramos de que la relación entre el rendimiento y la latencia es mucho más sutil que eso, ya menudo las métricas son muy contra-intuitivas. Imagine Un envío de mensajes a B. (Vea la Figura 24.2.) El tiempo total de la prueba es de 6 segundos. Se han pasado 5 mensajes. Por lo tanto, el rendimiento es de 0,83 msgs / s (5/6) y la latencia es de 1,2 segundos (6/5), a la derecha Eche un vistazo al diagrama de nuevo. Se tarda un tiempo diferente para que cada mensaje pase de A a B: 2 segundos, 2,5 segundos, 3 segundos, 3,5 segundos, 4 segundos. El promedio es de 3 segundos, que está bastante lejos de nuestro cálculo original de 1,2 segundos. Este ejemplo muestra las concepciones erróneas que las personas están inclinadas a hacer intuitivamente acerca de las métricas de rendimiento. Ahora eche un vistazo al rendimiento. El tiempo total de la prueba es de 6 segundos. Sin embargo, en A toma sólo 2 segundos para enviar todos los mensajes. Desde la perspectiva, el rendimiento es de 2,5 msgs / s (5/2). En B toma 4 segundos para recibir todos los mensajes. Por lo tanto, desde la perspectiva de Bs, el rendimiento es de 1,25 ms / s (5/4). Ninguno de estos números coincide con nuestro cálculo original de 1,2 ms / seg. Para hacer una larga historia corta, la latencia y el rendimiento son dos métricas diferentes que mucho es obvio. Lo importante es entender la diferencia entre los dos y su relación mutua. Latencia se puede medir sólo entre dos puntos diferentes en el sistema No hay tal cosa como la latencia en el punto A. Cada mensaje tiene su propia latencia. Usted puede promediar las latencias de varios mensajes sin embargo, no hay tal cosa como la latencia de una corriente de mensajes. El rendimiento, por el contrario, puede medirse sólo en un único punto del sistema. Hay un rendimiento en el emisor, hay un rendimiento en el receptor, hay un rendimiento en cualquier punto intermedio entre los dos, pero no hay tal cosa como el rendimiento general de todo el sistema. Y el rendimiento tiene sentido sólo para un conjunto de mensajes theres no hay tal cosa como el rendimiento de un único mensaje. En cuanto a la relación entre el rendimiento y la latencia, resulta que realmente hay una relación sin embargo, la fórmula implica integrales y no lo discutiremos aquí. Para más información, lea la literatura sobre la teoría de colas. Hay muchas más trampas en la evaluación comparativa de los sistemas de mensajería que no vamos más allá. El estrés debe ser colocado en la lección aprendida: Asegúrese de entender el problema que está resolviendo. Incluso un problema tan simple como hacerlo rápido puede tomar mucho trabajo para entender correctamente. Cuál es más, si usted no entiende el problema, usted es probable construir las suposiciones implícitas y los mitos populares en su código, haciendo la solución o bien defectuoso o por lo menos mucho más complejo o mucho menos útil que podría posiblemente ser. 24.4. Camino crítico Descubrimos durante el proceso de optimización que tres factores tienen un impacto crucial en el rendimiento: Número de asignaciones de memoria Número de llamadas al sistema Modelo de concurrencia Sin embargo, no todas las asignaciones de memoria ni todas las llamadas al sistema tienen el mismo efecto en el rendimiento. El rendimiento que nos interesa en los sistemas de mensajería es el número de mensajes que podemos transferir entre dos puntos finales durante un período de tiempo determinado. Alternativamente, podemos estar interesados ​​en cuánto tiempo tarda un mensaje en pasar de un extremo a otro. Sin embargo, dado que OslashMQ está diseñado para escenarios con conexiones de larga duración, el tiempo que tarda en establecer una conexión o el tiempo necesario para manejar un error de conexión es básicamente irrelevante. Estos eventos ocurren muy raramente y por lo tanto su impacto en el rendimiento general es insignificante. La parte de una base de código que se utiliza con mucha frecuencia, una y otra vez, se llama la optimización de ruta crítica debe centrarse en la ruta crítica. Echemos un vistazo a un ejemplo: OslashMQ no está muy optimizado con respecto a las asignaciones de memoria. Por ejemplo, al manipular cadenas, a menudo asigna una nueva cadena para cada fase intermedia de la transformación. Sin embargo, si nos fijamos estrictamente en el pathmdash crítico el mensaje real passingmdashwell averiguar que no utiliza casi ninguna asignación de memoria. Si los mensajes son pequeños, es sólo una asignación de memoria por 256 mensajes (estos mensajes se mantienen en un único bloque de memoria asignado grande). Si, además, la corriente de mensajes es constante, sin grandes picos de tráfico, el número de asignaciones de memoria en la ruta crítica cae a cero (los fragmentos de memoria asignados no se devuelven al sistema, sino que se vuelven a usar una y otra vez) . Lección aprendida: optimizar donde hace la diferencia. Optimizar piezas de código que no están en el camino crítico es un esfuerzo desperdiciado. 24,5. Asignar memoria Asumiendo que toda la infraestructura fue inicializada y que se ha establecido una conexión entre dos puntos finales, sólo hay una cosa que asignar al enviar un mensaje: el mensaje mismo. Por lo tanto, para optimizar el camino crítico tuvimos que mirar cómo los mensajes son asignados y pasados ​​arriba y abajo de la pila. Su conocimiento común en el campo de redes de alto rendimiento que el mejor rendimiento se logra equilibrando cuidadosamente el costo de la asignación de mensajes y el costo de la copia de mensajes (por ejemplo, hal. inria. fr/docs/00/29/28/31/ PDF / Open-MX-IOAT. pdf ver diferente manejo de mensajes pequeños, medianos y grandes). Para mensajes pequeños, copiar es mucho más barato que asignar memoria. No tiene sentido asignar ningún nuevo trozo de memoria en absoluto y en su lugar copiar el mensaje a la memoria preallocated siempre que sea necesario. Para los mensajes grandes, por otro lado, la copia es mucho más cara que la asignación de memoria. Tiene sentido asignar el mensaje una vez y pasar un puntero al bloque asignado, en lugar de copiar los datos. Este enfoque se denomina copia cero. OslashMQ maneja ambos casos de una manera transparente. Un mensaje OslashMQ está representado por un identificador opaco. El contenido de mensajes muy pequeños se codifica directamente en el identificador. Por lo tanto, hacer una copia del identificador copia realmente los datos del mensaje. Cuando el mensaje es mayor, se asigna en un búfer independiente y el identificador contiene sólo un puntero al búfer. Hacer una copia del identificador no da como resultado copiar los datos del mensaje, lo que tiene sentido cuando el mensaje es de megabytes de largo (Figura 24.3). Debe tenerse en cuenta que en el último caso el búfer es contado de referencia para que pueda ser referenciado por múltiples identificadores sin necesidad de copiar los datos. Lección aprendida: Al pensar en el rendimiento, no asuma que hay una sola mejor solución. Puede ocurrir que haya varias subclases del problema (por ejemplo, mensajes pequeños versus mensajes grandes), cada uno de los cuales tiene su propio algoritmo óptimo. 24,6. Batching Ya se ha mencionado que el gran número de llamadas de sistema en un sistema de mensajería puede resultar en un cuello de botella de rendimiento. En realidad, el problema es mucho más genérico que eso. Hay una penalización de rendimiento no trivial asociada con el desplazamiento de la pila de llamadas y, por lo tanto, al crear aplicaciones de alto rendimiento, es aconsejable evitar tanto atravesar la pila como sea posible. Considere la Figura 24.4. Para enviar cuatro mensajes, tiene que recorrer la pila de red completa cuatro veces (es decir, OslashMQ, glibc, límite de espacio de usuario / núcleo, implementación TCP, implementación de IP, capa Ethernet, el propio NIC y volver a copiar la pila). Sin embargo, si decide unir esos mensajes en un único lote, sólo habrá un recorrido de la pila (Figura 24.5). El impacto en el rendimiento del mensaje puede ser abrumador: hasta dos órdenes de magnitud, especialmente si los mensajes son pequeños y cientos de ellos pueden ser empaquetados en un solo lote. Por otro lado, el proceso por lotes puede tener un impacto negativo en la latencia. Tomemos, por ejemplo, el conocido algoritmo de Nagles, tal como se implementa en TCP. Retrasa los mensajes salientes durante cierto tiempo y fusiona todos los datos acumulados en un solo paquete. Obviamente, la latencia end-to-end del primer mensaje en el paquete es mucho peor que la latencia de la última. Por lo tanto, es común para las aplicaciones que necesitan consistentemente baja latencia para cambiar el algoritmo de Nagles. Su incluso común para apagar batching en todos los niveles de la pila (por ejemplo, NICs interrupción coalescencia característica). Pero, de nuevo, ningún proceso por lotes significa un desplazamiento extenso de la pila y da como resultado un bajo rendimiento de mensajes. Parece que estamos atrapados en un dilema de rendimiento versus latencia. OslashMQ intenta ofrecer latencias consistentemente bajas combinadas con alto rendimiento utilizando la siguiente estrategia: cuando el flujo de mensajes es escaso y no excede el ancho de banda de las pilas de red, OslashMQ convierte todos los lotes desactivados para mejorar la latencia. El trade-off aquí es algo más alto usagemdashwe de la CPU todavía tiene que recorrer la pila con frecuencia. Sin embargo, que no se considera un problema en la mayoría de los casos. Cuando la velocidad de mensajes excede el ancho de banda de la pila de red, los mensajes tienen que almacenarse en la memoria en cola hasta que la pila esté lista para aceptarlos. Cola significa que la latencia va a crecer. Si el mensaje pasa un segundo en la cola, la latencia de extremo a extremo será al menos un segundo. Lo que es peor, a medida que crece el tamaño de la cola, las latencias aumentarán gradualmente. Si el tamaño de la cola no está enlazado, la latencia puede superar cualquier límite. Se ha observado que aunque la pila de la red se sintoniza para la latencia más baja posible (el algoritmo de Nagles se apaga, la interrupción de la NIC se desactiva, etc.), las latencias pueden seguir siendo tristes debido al efecto de cola, como se ha descrito anteriormente. En tales situaciones, tiene sentido iniciar el proceso de dosificación de manera agresiva. No hay nada que perder, ya que las latencias ya son altas de todos modos. Por otro lado, el procesamiento agresivo mejora el rendimiento y puede vaciar la cola de mensajes pendientes que, a su vez, significa que la latencia disminuirá gradualmente a medida que disminuya el retraso en la cola. Una vez que no hay mensajes pendientes en la cola, el proceso por lotes se puede desactivar para mejorar aún más la latencia. Una observación adicional es que el lote debe hacerse solamente en el nivel más alto. Si los mensajes se procesan por lotes, las capas inferiores no tienen nada que procesar de todos modos, por lo que todos los algoritmos de proceso por lotes que se encuentran debajo no hacen nada excepto introducir latencia adicional. Lección aprendida: Para obtener un rendimiento óptimo combinado con un tiempo de respuesta óptimo en un sistema asíncrono, desactive todos los algoritmos de dosificación en las capas bajas de la pila y el lote en el nivel superior. Lote sólo cuando los nuevos datos llegan más rápido de lo que pueden ser procesados. 24,7. Visión general de la arquitectura Hasta este punto nos hemos centrado en los principios genéricos que hacen OslashMQ rápido. A partir de ahora, eche un vistazo a la arquitectura actual del sistema (Figura 24.6). El usuario interactúa con OslashMQ utilizando los llamados sockets. Son bastante similares a los sockets TCP, la principal diferencia es que cada socket puede manejar la comunicación con varios pares, un poco como unidos enchufes UDP hacer. El objeto socket vive en el subproceso usuarios (consulte la discusión de modelos de subprocesamiento en la sección siguiente). Aparte de eso, OslashMQ está ejecutando múltiples subprocesos de trabajo que manejan la parte asíncrona de la comunicación: lectura de datos de la red, enqueueing de mensajes, aceptación de conexiones entrantes, etc. Hay varios objetos que viven en los subprocesos de trabajo. Cada uno de estos objetos pertenece exactamente a un objeto principal (la propiedad se indica mediante una línea completa simple en el diagrama). El padre puede vivir en un hilo diferente que el niño. La mayoría de los objetos son propiedad directa de sockets sin embargo, hay un par de casos en que un objeto es propiedad de un objeto que es propiedad de la toma. Lo que obtenemos es un árbol de objetos, con un tal árbol por zócalo. El árbol se utiliza durante el cierre ningún objeto puede cerrarse hasta que cierra a todos sus hijos. De esta manera, podemos garantizar que el proceso de cierre funcione como se esperaba, por ejemplo, que los mensajes salientes pendientes se envíen a la red antes de finalizar el proceso de envío. A grandes rasgos, hay dos tipos de objetos asíncronos: hay objetos que no están involucrados en el paso del mensaje y hay objetos que lo son. Los primeros tienen que ver principalmente con la gestión de conexiones. Por ejemplo, un objeto de escucha de TCP escucha las conexiones entrantes de TCP y crea un objeto de motor / sesión para cada nueva conexión. Del mismo modo, un objeto de conector TCP intenta conectarse al par TCP y cuando tiene éxito crea un motor / objeto de sesión para administrar la conexión. Cuando dicha conexión falla, el objeto conector intenta restablecerlo. Estos últimos son objetos que manejan la transferencia de datos en sí. Estos objetos están compuestos de dos partes: el objeto de sesión es responsable de interactuar con el socket OslashMQ y el objeto de motor es responsable de la comunicación con la red. Sólo hay un tipo de objeto de sesión, pero hay un tipo de motor diferente para cada protocolo subyacente soporta OslashMQ. Por lo tanto, tenemos motores TCP, motores IPC (inter-proceso de comunicación), motores PGM (un protocolo de multidifusión confiable, véase RFC 3208), etc El conjunto de motores es extensiblemdashin en el futuro podemos optar por implementar, por ejemplo, un motor WebSocket O un motor SCTP. Las sesiones están intercambiando mensajes con los sockets. Hay dos direcciones para pasar mensajes y cada dirección es manejada por un objeto de tubería. Cada tubo es básicamente una cola libre de bloqueo optimizada para el paso rápido de mensajes entre hilos. Finalmente, hay un objeto de contexto (discutido en las secciones anteriores pero no mostrado en el diagrama) que contiene el estado global y es accesible por todos los sockets y todos los objetos asíncronos. 24,8. Concurrency Model Uno de los requisitos para OslashMQ era aprovechar las cajas multi-core en otras palabras, para escalar el rendimiento linealmente con el número de núcleos de CPU disponibles. Nuestra experiencia anterior con sistemas de mensajería mostró que el uso de múltiples hilos de una manera clásica (secciones críticas, semáforos, etc.) no genera mucha mejora en el rendimiento. De hecho, una versión de múltiples hilos de un sistema de mensajería puede ser más lenta que una de un solo hilo, incluso si se mide en una caja multi-núcleo. Los hilos individuales simplemente pasan demasiado tiempo esperando uno al otro mientras, al mismo tiempo, provocan una gran cantidad de cambios de contexto que ralentizan el sistema. Teniendo en cuenta estos problemas, hemos decidido optar por un modelo diferente. El objetivo era evitar bloquear por completo y dejar que cada hilo funcionara a toda velocidad. La comunicación entre hilos debía proporcionarse a través de mensajes asincrónicos (eventos) pasados ​​entre los hilos. Esto, como saben los iniciados, es el modelo de actor clásico. La idea era lanzar un hilo de trabajo por procesador de la CPU, teniendo dos hilos compartiendo el mismo núcleo, sólo significaría mucho cambio de contexto sin ninguna ventaja en particular. Cada objeto OslashMQ interno, como por ejemplo un motor TCP, estaría estrechamente unido a un hilo de trabajo particular. That, in turn, means that theres no need for critical sections, mutexes, semaphores and the like. Additionally, these OslashMQ objects wont be migrated between CPU cores so would thus avoid the negative performance impact of cache pollution (Figure 24.7 ). This design makes a lot of traditional multi-threading problems disappear. Nevertheless, theres a need to share the worker thread among many objects, which in turn means there has to be some kind of cooperative multitasking. This means we need a scheduler objects need to be event-driven rather than being in control of the entire event loop we have to take care of arbitrary sequences of events, even very rare ones we have to make sure that no object holds the CPU for too long etc. In short, the whole system has to become fully asynchronous. No object can afford to do a blocking operation, because it would not only block itself but also all the other objects sharing the same worker thread. All objects have to become, whether explicitly or implicitly, state machines. With hundreds or thousands of state machines running in parallel you have to take care of all the possible interactions between them andmdashmost importantlymdashof the shutdown process. It turns out that shutting down a fully asynchronous system in a clean way is a dauntingly complex task. Trying to shut down a thousand moving parts, some of them working, some idle, some in the process of being initiated, some of them already shutting down by themselves, is prone to all kinds of race conditions, resource leaks and similar. The shutdown subsystem is definitely the most complex part of OslashMQ. A quick check of the bug tracker indicates that some 30--50 of reported bugs are related to shutdown in one way or another. Lesson learned: When striving for extreme performance and scalability, consider the actor model its almost the only game in town in such cases. However, if you are not using a specialised system like Erlang or OslashMQ itself, youll have to write and debug a lot of infrastructure by hand. Additionally, think, from the very beginning, about the procedure to shut down the system. Its going to be the most complex part of the codebase and if you have no clear idea how to implement it, you should probably reconsider using the actor model in the first place. 24.9. Lock-Free Algorithms Lock-free algorithms have been in vogue lately. They are simple mechanisms for inter-thread communication that dont rely on the kernel-provided synchronisation primitives, such as mutexes or semaphores rather, they do the synchronisation using atomic CPU operations, such as atomic compare-and-swap (CAS). It should be understood that they are not literally lock-freemdashinstead, locking is done behind the scenes on the hardware level. OslashMQ uses a lock-free queue in pipe objects to pass messages between the users threads and OslashMQs worker threads. There are two interesting aspects to how OslashMQ uses the lock-free queue. First, each queue has exactly one writer thread and exactly one reader thread. If theres a need for 1-to - N communication, multiple queues are created (Figure 24.8 ). Given that this way the queue doesnt have to take care of synchronising the writers (theres only one writer) or readers (theres only one reader) it can be implemented in an extra-efficient way. Second, we realised that while lock-free algorithms were more efficient than classic mutex-based algorithms, atomic CPU operations are still rather expensive (especially when theres contention between CPU cores) and doing an atomic operation for each message written and/or each message read was slower than we were willing to accept. The way to speed it upmdashonce againmdashwas batching. Imagine you had 10 messages to be written to the queue. It can happen, for example, when you received a network packet containing 10 small messages. Receiving a packet is an atomic event you cannot get half of it. This atomic event results in the need to write 10 messages to the lock-free queue. Theres not much point in doing an atomic operation for each message. Instead, you can accumulate the messages in a pre-write portion of the queue thats accessed solely by the writer thread, and then flush it using a single atomic operation. The same applies to reading from the queue. Imagine the 10 messages above were already flushed to the queue. The reader thread can extract each message from the queue using an atomic operation. However, its overkill instead, it can move all the pending messages to a pre-read portion of the queue using a single atomic operation. Afterwards, it can retrieve the messages from the pre-read buffer one by one. Pre-read is owned and accessed solely by the reader thread and thus no synchronisation whatsoever is needed in that phase. The arrow on the left of Figure 24.9 shows how the pre-write buffer can be flushed to the queue simply by modifying a single pointer. The arrow on the right shows how the whole content of the queue can be shifted to the pre-read by doing nothing but modifying another pointer. Lesson learned: Lock-free algorithms are hard to invent, troublesome to implement and almost impossible to debug. If at all possible, use an existing proven algorithm rather than inventing your own. When extreme performance is required, dont rely solely on lock-free algorithms. While they are fast, the performance can be significantly improved by doing smart batching on top of them. 24.10. API The user interface is the most important part of any product. Its the only part of your program visible to the outside world and if you get it wrong the world will hate you. In end-user products its either the GUI or the command line interface. In libraries its the API. In early versions of OslashMQ the API was based on AMQPs model of exchanges and queues. (See the AMQP specification .) From a historical perspective its interesting to have a look at the white paper from 2007 that tries to reconcile AMQP with a brokerless model of messaging. I spent the end of 2009 rewriting it almost from scratch to use the BSD Socket API instead. That was the turning point OslashMQ adoption soared from that point on. While before it was a niche product used by a bunch of messaging experts, afterwards it became a handy commonplace tool for anybody. In a year or so the size of the community increased tenfold, some 20 bindings to different languages were implemented, etc. The user interface defines the perception of a product. With basically no change to the functionalitymdashjust by changing the APImdashOslashMQ changed from an enterprise messaging product to a networking product. In other words, the perception changed from a complex piece of infrastructure for big banks to hey, this helps me to send my 10-byte-long message from application A to application B. Lesson learned: Understand what you want your project to be and design the user interface accordingly. Having a user interface that doesnt align with the vision of the project is a 100 guaranteed way to fail. One of the important aspects of the move to the BSD Sockets API was that it wasnt a revolutionary freshly invented API, but an existing and well-known one. Actually, the BSD Sockets API is one of the oldest APIs still in active use today it dates back to 1983 and 4.2BSD Unix. Its been widely used and stable for literally decades. The above fact brings a lot of advantages. Firstly, its an API that everybody knows, so the learning curve is ludicrously flat. Even if youve never heard of OslashMQ, you can build your first application in couple of minutes thanks to the fact that you are able to reuse your BSD Sockets knowledge. Secondly, using a widely implemented API enables integration of OslashMQ with existing technologies. For example, exposing OslashMQ objects as sockets or file descriptors allows for processing TCP, UDP, pipe, file and OslashMQ events in the same event loop. Another example: the experimental project to bring OslashMQ-like functionality to the Linux kernel turned out to be pretty simple to implement. By sharing the same conceptual framework it can re-use a lot of infrastructure already in place. Thirdly and probably most importantly, the fact that the BSD Sockets API survived almost three decades despite numerous attempts to replace it means that there is something inherently right in the design. BSD Sockets API designers havemdashwhether deliberately or by chancemdashmade the right design decisions. By adopting the API we can automatically share those design decisions without even knowing what they were and what problem they were solving. Lesson learned: While code reuse has been promoted from time immemorial and pattern reuse joined in later on, its important to think of reuse in an even more generic way. When designing a product, have a look at similar products. Check which have failed and which have succeeded learn from the successful projects. Dont succumb to Not Invented Here syndrome. Reuse the ideas, the APIs, the conceptual frameworks, whatever you find appropriate. By doing so you are allowing users to reuse their existing knowledge. At the same time you may be avoiding technical pitfalls you are not even aware of at the moment. 24.11. Messaging Patterns In any messaging system, the most important design problem is that of how to provide a way for the user to specify which messages are routed to which destinations. There are two main approaches, and I believe this dichotomy is quite generic and applicable to basically any problem encountered in the domain of software. One approach is to adopt the Unix philosophy of do one thing and do it well. What this means is that the problem domain should be artificially restricted to a small and well-understood area. The program should then solve this restricted problem in a correct and exhaustive way. An example of such approach in the messaging area is MQTT. Its a protocol for distributing messages to a set of consumers. It cant be used for anything else (say for RPC) but it is easy to use and does message distribution well. The other approach is to focus on generality and provide a powerful and highly configurable system. AMQP is an example of such a system. Its model of queues and exchanges provides the user with the means to programmatically define almost any routing algorithm they can think of. The trade-off, of course, is a lot of options to take care of. OslashMQ opts for the former model because it allows the resulting product to be used by basically anyone, while the generic model requires messaging experts to use it. To demonstrate the point, lets have a look how the model affects the complexity of the API. What follows is implementation of RPC client on top of a generic system (AMQP): On the other hand, OslashMQ splits the messaging landscape into so-called messaging patterns. Examples of the patterns are publish/subscribe, request/reply or parallelised pipeline. Each messaging pattern is completely orthogonal to other patterns and can be thought of as a separate tool. What follows is the re-implementation of the above application using OslashMQs request/reply pattern. Note how all the option tweaking is reduced to the single step of choosing the right messaging pattern ( REQ ): Up to this point weve argued that specific solutions are better than generic solutions. We want our solution to be as specific as possible. However, at the same time we want to provide our customers with as wide a range of functionality as possible. How can we solve this apparent contradiction The answer consists of two steps: Define a layer of the stack to deal with a particular problem area (e. g. transport, routing, presentation, etc.). Provide multiple implementations of the layer. There should be a separate non-intersecting implementation for each use case. Lets have a look at the example of the transport layer in the Internet stack. Its meant to provide services such as transferring data streams, applying flow control, providing reliability, etc. on the top of the network layer (IP). It does so by defining multiple non-intersecting solutions: TCP for connection-oriented reliable stream transfer, UDP for connectionless unreliable packet transfer, SCTP for transfer of multiple streams, DCCP for unreliable connections and so on. Note that each implementation is completely orthogonal: a UDP endpoint cannot speak to a TCP endpoint. Neither can a SCTP endpoint speak to a DCCP endpoint. It means that new implementations can be added to the stack at any moment without affecting the existing portions of the stack. Conversely, failed implementations can be forgotten and discarded without compromising the viability of the transport layer as a whole. The same principle applies to messaging patterns as defined by OslashMQ. Messaging patterns form a layer (the so-called scalability layer) on top of the transport layer (TCP and friends). Individual messaging patterns are implementations of this layer. They are strictly orthogonalmdashthe publish/subscribe endpoint cant speak to the request/reply endpoint, etc. Strict separation between the patterns in turn means that new patterns can be added as needed and that failed experiments with new patterns wont hurt the existing patterns. Lesson learned: When solving a complex and multi-faceted problem it may turn out that a monolithic general-purpose solution may not be the best way to go. Instead, we can think of the problem area as an abstract layer and provide multiple implementations of this layer, each focused on a specific well-defined use case. When doing so, delineate the use case carefully. Be sure about what is in the scope and what is not. By restricting the use case too aggressively the application of your software may be limited. If you define the problem too broadly, however, the product may become too complex, blurry and confusing for the users. 24.12. Conclusion As our world becomes populated with lots of small computers connected via the Internetmdashmobile phones, RFID readers, tablets and laptops, GPS devices, etc. mdashthe problem of distributed computing ceases to be the domain of academic science and becomes a common everyday problem for every developer to tackle. The solutions, unfortunately, are mostly domain-specific hacks. This article summarises our experience with building a large-scale distributed system in a systematic manner. It focuses on problems that are interesting from a software architecture point of view, and we hope that designers and programmers in the open source community will find it useful. Back to top Back to The Architecture of Open Source Applications. Introduction The financial sector lives off messaging technology. On quotWall Streetquot (the global stock trading business), capacity and latency are everything. Current infrastructure, highly tuned to get million-message per second throughputs, and sub-millisecond latencies, still fails when trading gets frantic. Huge amounts of money depend on being the first to get data, and the first to trade. The stock trading business is evolving dramatically. Penny pricing generates more data. New US and EU regulations increase the number of parties involved in financial markets. New algorithmic trading technologies increase the demand for up-to-date stock data and icrease number of orders. While the existing infrastructure can double in capacity or speed per 18 months, traffic is expected to grow by 20 times over the next three years 1 . In the same time, prices for messaging technology are steadily rising. Messaging middleware - software that connects applications or pieces of applications in a generalised plug-and-play fashion - is one of the last big-ticket items still not turned into a commodity by the Internet age of cheap software. Mainframes got much of their power from clever messaging, transaction processing systems like IBM CICS. But today even 1980s-standard middleware - unlike databases, operating systems, compilers, editors, GUIs, and so on - is still not widely available to ordinary developers. The software industry is producing various business applications and pieces of applications, and the tools to make these, in ever greater quantities, and ever lower prices, but the messaging bit is still missing. The lack of a way to connect these applications has become not just an unconquered terrain, but also a serious bottleneck to growth, especially for new start-ups that could in theory compete aggressively with larger, older firms, if they were able to cheaply combine existing blocks of software. This frustration is visible in many markets and has lead to the growth of messaging-over-HTTP (SOAP), and other compromises. Architectures like SOAP do work, but they dont solve the two main issues of a enterprise-level messaging, namely routing and queuing. Thus businesses who use such technologies cannot scale, and cannot compete in really large markets, unless they write their own messaging software, or buy a commercial product. Various other standardisation attempts were made to commoditise the market: CORBA, JMS and lately AMQP, CORBA being unsuccessful because of RPC metaphor that doesnt suit the needs of financial markets, JMS succeeding in Java world, but unable to expand any further and AMQP still being a big unknown. The increasing demand, and lack of real competition shows in the financial statements of high-end messaging vendors like Tibco Software Inc: quotTotal revenue in the first quarter of fiscal year 2007 compared to the same quarter last year increased by 11.0 million or 10. The increase was comprised of a 7.0 million or 11 increase in service and maintenance revenue and by a 4.0 million or 8 increase in license revenue. quot 2 Tibco customers report that license fees are increasing, year on year. The market The global stock trading market is primary focus of MQ because thats where most emphasis is placed on messaging, most resources are accumulated and most edge-cutting technologies are used. The main characteristic of the market is hunger for fast delivery. Every millisecond the stock quote or the trade order is faster than the competing one translates into direct financial profit, so the firms involved are naturally eager for any advantage they can get. Currently, in the stock-trading business traffic load is so high and latency so critical, that the middleware has to be highly optimised. Latencies are given in microseconds and throughputs in millions of messages per second8230 In spite of that, trading often experiences problems when message load peaks. Latency can suddenly drop to seconds (or even tens of seconds) and huge amounts of money can be lost as trades are delayed or fail. 3 The situation is getting worse for several reasons: In 2001, the NYSE and NASDAQ switched from pricing their stocks in 1/16th dollar units to single cent units. This so-called quotpenny pricingquot means stock markets produce more data and this data must be shifted across networks. Both in the US and EU, regulators are forcing financial markets to compete more openly and aggressively, in the interests of consumers. For example US SEC regulatory changes allow new firms to act as intermediaries in the stock trading sector while the EUs Markets in Financial Instruments Directive (MiFID) 4 is expected to increase stock-trading traffic rates in EU to match the volumes seen in US after Reg NMS 5 . Many new and aggressive firms are entering the market, especially building or using algorithmic trading platforms. Algorithmic trading executes big amount of low-volume orders as opposed to small amount of high-volume orders executed by traditional human traders. So we have increased data flows, to more participants, who are pushing to develop new business models which depend on getting that data rapidly, detecting temporary market anomalies, and responding to it (with trades) before their competitors. A more flexible regulatory environment is opening previously protected markets to new competition. Overall, we see an arms race for bandwidth and latency in which better technology translates directly into more profits. 6 Message traffic is expected to grow significantly in the near term - we have heard different figures of up to 30 times over the next three years - and existing systems can only double capacity every 18 months. There are many attempts to solve this emerging issue. The most dramatic improvements in performance come from replacing the classic central broker with a peer-to-peer architecture in which messages can flow directly across the network with no extra hops. Not all messaging systems can adapt their architecture in this way. Apart from architecture, the obvious place to optimise messaging is in the quotstackquot, i. e. the layers that separate the application program from the physical network. The software itself is already heavily optimised in most cases, so vendors are shifting to other options, such as: Optimising network architecture by connectivity providers to get better latencies, including moving message consumers close (in network terms) to the message producers 7. 8 . Clients moving from consolidated stock quote feeds to direct connectivity to the exchanges 9 Optimising formats in which data are passed (FIX/FAST 10 ) Providing full-blown hardware solutions (Tervela, Exegy, etc.) Replacing the physical transport layer (Infiniband 11. 10GB Ethernet) Optimising existing networking hardware. TCP offload engines, Intels I/OAT technology 12. etc. Modifying the OS to handle the messages in real-time. Various real-time OSs, like Novells SLERT 13 Modifying the OS to use more efficient messaging stack: Asynchronous I/O, SDP, various zero-copy techniques etc. Using multicast to distribute stock quotes on the clients LAN As well as these optimisations, which focus on individual aspects of the messaging stack or architecture, we also see attempts that look at the problem as a whole: Intels Low Latency Lab 14 Securities Technology Analysis Center (STAC) 15 Various measurement amp monitoring solutions (Endace etc.) Highly optimised products with extensive hardware support become very expensive. Only the largest trading firms can afford the full range of products and even for these firms, costs remain a persistent concern. For the smaller firms, many of the solutions are simply not an option. Opportunities In this section we look at the opportunities for new high-performance messaging products such as those we are building. High-performance take-out The first and most obvious target is any firm using high-end commercial middleware for stock trading, where we can provide a cheaper equivalent. This market is cost-sensitive and in our experience it is willing to absorb change and risk in order to get a compelling price and/or performance advantage over their competitors. Further, there are many firms who cannot afford these products, but would use them if the cost was set lower. Zipfs Law (usually used for language but also applicable to business sizes) suggests that the number of firms and their size follows an inverse power ratio, so offering a product at 20 the price of the high-cost market leaders should open a market five times as large. (In fact its probably not this large, because smaller firms will buy or rent trading platforms rather than try to build their own.) Trading platforms Trading platforms are software applications that trading firms can buy ready-made, rather than build themselves using messaging middleware. Given the demand for cheaper, faster trading, there is a large market for these platforms. Obviously a firm that builds a trading platform is sensitive to the cost of the messaging it uses and these firms provide a market for our planned products. Investment banks Investment banks build their own trading systems and (from our limited experience) like to have control over the technology they use. Standards-based systems are highly attractive here. The calculation is that a standard technology is easier to control, and is served by a larger market of cheaper experts. Any AMQP solution has immediate attraction. Cost is always a driver as well but for firms that do significant development around the messaging, reduction of secondary costs (such as the number and cost of in-house consultants) is an important aspect. It becomes clear why JPMorganChase was motivated to push and invest in the AMQP process, even taking considerable risks at the time: AMQP enables very large savings on IT expenditure, for messaging licenses, custom development, operational control, and so on. We can deliver a much lower-risk proposal to other investment banks, but with the same kinds of benefits. Data consolidators The stock trading world connects many exchanges (NASDAQ, NYSE, etc.) to many clients. Large clients make separate connections to each exchange, but most work via data consolidators, firms like Reuters who provide unified streams from many sources. Todays consolidators run highly-tuned custom messaging software, it is not standards-based, and has little scope for getting cheaper and faster. It can get faster, but only at high cost, which punishes those firms that stick with custom messaging, and gives an advantage to those firms using standards-based messaging, which spreads the costs and leverages far more work on performance. There is a definite opportunity for opening this market, and allowing new firms to compete as data consolidators, using our high-performance products to carry quotes to clients. New US regulations are opening this market to real competition. Exchanges The exchanges (stock exchanges, currency exchanges, commodities, etc.) are heavily impacted by the growth in demand for their services. It seems inevitable that standards at the edges will slowly force their way into the center, and we should be able to follow with product offerings. Also, new types of trading venues are emerging (ATSs, MTFs and dark pools 16 ) that gradually take still greater share of the market from the traditional exchanges. Given that this trend is quite new and still gaining momentum, we expect to see increasing demand for high-end messaging systems on this market. Moving the value to different markets One of the goals of MQ is to use money, resources and experience accumulated during low-latency arms race in stock-trading business to deliver free high-end general-purpose messaging solution to the rest of IT sector. Some of the areas where MQ may prove useful follow. Business and institutional messaging Sending payments, doing business-to-business communication, passing documents within governmental organisations etc. is the primary market to focus on apart of stock trading. The reason is that this is the field where messaging is used traditionally, with lot of experienced IT personel aware of messaging and using it for a long time. It should be also taken into account that even applications that dont use messaging proper may be still sending messages by different means. Consider an application located at place A writing a record to remote database server and another one at place B reading the record. In fact, there was a message sent from A to B, even though the programmer might not be aware of it. Even inter-process and inter-thread communication can be considered messaging. Synchronising different applications by copying files to remote destinations once a day can be considered messaging as well (although it is a spectacularly low-latency one). Basically any application made for financial or institutional sector needs some kind of messaging and the cost of the implementation varies between 10 and 30 per cent of the total project cost, so using existing standards-based middleware implementation seems to be a rather good investment. Although low latency is not a key requirement in this sphere, we expect that growing transaction rates (consider regulations like EUs SEPA 17 and standardisation efforts like TWIST 18 ) will slowly force financial institutions to adopt high-performance messaging solutions, thus causing the current small slice of the messaging market addressed by high-performance solutions will steadily grow, until it ultimately reaches 100. Embedded systems Embedded systems often have real-time requirements similar to those seen in stock-trading business. Consider, for example, an equipment measuring some critical value in a technological process. The data have to be delivered to the unit controlling the process within 1160ms, otherwise the whole process will be spoiled. Embedded systems dont usually need the throughput provided by stock-trading stacks, however, if the latency, reliability and deterministic delivery times are guaranteed, they can take advantage of it, even though it doesnt use all the bandwidth capacity available. Multimedia Same remark about real-time requirements applies to multimedia (streaming audio and video, teleconferencing, etc.). As opposed to embedded systems, latency is not that critical, the paramount being deterministic delivery time and high throughput. In the future we may find out that lot-of-small-messages model of stock-trading apps is incompatible with stream-based multimedia approach. However, we dont believe this is the case. To test the hypothesis, weve built proof-of-concept teleconferencing application over AMQP and weve seen it perform smoothly. Grid computing Having almost the same requirements as stock trading, grid systems are natural area to employ MQ stack. Grids are icreasingly being used in financials 19 and - not surprisingly - in stock trading itself, providing a solution for computationally expensive problems like risk management and algorithmic trading 20 . The low-latency bubble The market for low-latency solutions is very lively and expanding these days. However, some have a feeling that the value of the market is overestimated and that low-latency arms races going on will result in the burst of the bubble, similar to dot-com crash of early 2000s. Lets examine possible causes of market breakdown: There are laws of physics that place lower bound on the latency. Specifically, speed of light cannot be exceeded and once the messaging hits this limit, there wont be much space for competition and low-latency arms race will come to its end. The costs for fast messaging are constantly growing. Once we hit the point where improving the latency will require investments exceeding the profits it can possibly yield, the flow of money into the market will end. Unreasonable spending on low-latency solutions can result in hysteria, once the still growing low-latency market starts shrinking. Hysteria can make the market plummet even below its real value. Our view of the problems above is following: Speed of light is certainly an ultimate barrier, however, as can be seen with microprocessors, barriers seen as ultimate are quite prone to be crossed over and over again. In messaging business for example, we see emerging proximity solutions (handling speed of light problem by placing interdependent applications physically close one to another) or the trend to optimise software part of the messaging stack thus removing endpoint latency rather than on-the-wire latency. In fact, we dont believe there are any real unpenetrable barriers to stop low-latency arms race at least in the next several years. Although costliness of the low-latency messaging grows steadily, it should be taken into account that technology price - both hardware and software - is steadily decreasing at the same time. What cost 100 last year, costs 50 today. So, even in stable, non-expanding market, where spending on IT keeps constant, there will be a demand for new solutions to keep pace with new technologies. Hysteria can happen at any time and theres no way to prevent it completely. However, as stock-trading messaging is in a way a world for itself, we expect hysteria to be restricted to this turbulent little market leaving the rest of messaging market intact. Thus the main victims will be the firms that provide specialised stock-trading solutions rather than general-purpose messaging. Specifically, MQ project, by taking advantage of the resources accumulated in stock-trading-focused IT market to develop general-purpose messaging solution can survive market breakdown by relying on its presence in different sectors of messaging market. Conclusion The primary focus of MQ starts with stock trading because this market has a well-defined and growing demand for high-end solutions, and the options for collaborations and return on investment are plentiful. However, the construction of a cost-efficient, standards-based messaging system that can compete head-on with the best in the world opens doors into many other domains as well. Comments: 0

No comments:

Post a Comment