<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohanad Kaleia on Medium]]></title>
        <description><![CDATA[Stories by Mohanad Kaleia on Medium]]></description>
        <link>https://medium.com/@m.kaleia?source=rss-8dad05a7387b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6xSm0QyhvupQ7wak_KI7Ug.jpeg</url>
            <title>Stories by Mohanad Kaleia on Medium</title>
            <link>https://medium.com/@m.kaleia?source=rss-8dad05a7387b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:31:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.kaleia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[re]Build scalable IoT system]]></title>
            <link>https://medium.com/@m.kaleia/re-build-scalable-iot-system-91b7eac71935?source=rss-8dad05a7387b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b7eac71935</guid>
            <category><![CDATA[scaleup]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Mohanad Kaleia]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 06:53:50 GMT</pubDate>
            <atom:updated>2019-10-21T06:53:50.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Two years ago I worked on an Internet of Things system that does reading weather information from weather stations and submit the readings into a server to record these readings into a database and visualize them into a UI. (I got to work only on the backend side of it)</p><p>The project was pretty easy. we have 15 weather stations, every station is attached to Linux box <a href="https://beagleboard.org/bone">BeagleBone</a> that reads the weather data from the sensors and send these data over a bidirectional WebSocket connection with the server. The server reads the data and stores them in a simple relational database. The system is very small and no need to scale it at this size, but just and to learn new stuff I decided to build a similar system that can scale if the number of stations got increased.</p><p>The rest of this post I will explain the proposed architecture along with the code used in the demo implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*iLOUZySYlHx5izIF.gif" /></figure><h3>The architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-T-XOXnvBSd8ubK.png" /><figcaption>The proposed architecture for the system</figcaption></figure><p>In this system, we have three main components, the weather stations, server apps, and a datastore. The weather stations connect with the server and send messages through a bidirectional WebSocket connection. The server receives the incoming messages from clients and stores them in the database. For authentication, we will need HTTP API with JWT to authenticate clients. This is a very high-level view, let&#39;s dive little deeper into each component:</p><h3>Weather Station</h3><p>The station (client) is a Linux box connected to a weather station. This weather station reads the temperature, humidity, wind speed, and other information related to the weather. We need to read the weather data every x amount of time and send it immediately to the server, if the internet connection between the station and the server is not available we should store the messages locally and send them once the internet is back.</p><p>For saving messages in case of lost internet connection, I used a <a href="https://en.wikipedia.org/wiki/Message_queue">message queue</a> that can be used as a work or job queue, where we have a producer which reads weather data and enqueue the weather data as a message in the queue and consumers that read messages from the queue and send them to the server.</p><p>The same message queue can be configured to preserve messages incase the consumers fail in sending the messages to the server and try to send them again later once the issue is solved (the internet is back).</p><p>I will talk more about message queue implementation later.</p><h3>Server-side</h3><p>The server side consists of two main components, the message queue WebSocket app, and the auth app. The message queue app is used to receive messages from the clients and store them in the db. The auth app is used to authenticate the clients before they can send any message.</p><p><strong>Websocket app: </strong>a WebSocket connection has been used to create a bidirectional connection between the client and the server and a message queue has been used to store the messages in a job queue wherein its simplest form the workers are just pulling messages from the queue and store them in the datastore. The messages in the queue containing a timestamp that is created by the clients when the message is created.</p><p><strong>Auth app:</strong> for any client to be able to send messages it has to be authenticated. JSON Web Authentication <a href="https://jwt.io/">JWT</a> has been used to provide authentication. An HTTP API can be used to send a token when the client login with its account_id and password. Then the client includes this token with every message sent to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*BIiya5dbGav_3Pgr.png" /><figcaption>Auth process</figcaption></figure><p>The idea of JWT auth is very simple, the client sends a post request to the server `/login` endpoint with its username and password, the server verifies the user information and returns a token that is generated by the server using its private key. Then the client stores this token and send it along with every message. When the server receives a message it tries to decrypt the token to verify the token.</p><h3>Datastore</h3><p>To store the data it is good to use a reliable engine like Postgresql or Mysql. For me, since the purpose of this demo was not for production I used a document-based database called <a href="https://tinydb.readthedocs.io/en/latest/index.html">tinydb</a> (it works!) I created two tables one for the weather and the other one for the users. Basically, just dump the weather messages coming from the client into the weather table in its JSON format. Now, let&#39;s move to the implementation part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*I2zK9gYZTJDrPdae.gif" /></figure><h3>Implementation</h3><p>Here is the stack I used for the implementation:</p><ul><li><strong>Flask</strong>: used to deliver endpoints required for authentication (web app)</li><li><a href="https://www.rabbitmq.com/"><strong>RabbitMQ</strong></a>: I used RabbitMQ for the message queue, (easy enough with nice documentation)</li><li><strong>Python</strong></li><li><a href="https://tinydb.readthedocs.io/en/latest/index.html"><strong>Tinydb</strong></a>: document-based database, not recommended for production at all, I used for the quick demo only</li></ul><h3>Requirements</h3><p>Before I start the implementation, you will need to have the following stuff installed, Python, <a href="https://www.rabbitmq.com/download.html">RabbitMQ server.</a> The rest of the libraries you can install in your virtual env.</p><p>For the requirements you can run:</p><p><em>pip install -r requirements.txt</em></p><p>I structured the project in a very simple way:</p><ul><li><strong>server.py</strong> (this is the WebSocket server)</li><li><strong>station.py</strong> (this file should run on the clients)</li><li><strong>config.py</strong></li><li><strong>app.py</strong>: authentication Flask app is in here</li><li><strong>user.py</strong>: the logic to create, authenticate a user</li></ul><h3>Client</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a8c65bc466ef9fe0f76956cae1281e9/href">https://medium.com/media/3a8c65bc466ef9fe0f76956cae1281e9/href</a></iframe><p>I don’t want to bore you with the code explanation, pretty sure you can read it and understand it your self. But the headlines are like the following:</p><ol><li>For the sake of the demo, I don’t have here a real weather station, so in the Station class I made a read method that a random integer that represents the temperature</li><li>Also in the same class, we have the login method that sends a post request to the server with the username and the password to obtain the token and store it in the Station object.</li><li>On the client-side, we create a queue named it as task_queue this queue will be used to dump the messages in and send them to the server. To do that we create a producer that reads weather temperature from the weather station and store it in the queue. We have a consumer that consumer messages from the queue and send them to the server</li><li>The consumer sends the messages to a message queue on the server named message_queue</li><li>Note inline 86 and 96 we set the queue to preserver the messages in case something bad happened (the client went off, or there is no internet connection)</li></ol><h3>Server</h3><p>Cool.. we reached the server-side, it is simpler than the client-side I think :)</p><p>It has two parts as we saw before, the message queue and the auth app. We will start with the web socket part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ff2dd00de11913ab6e6cc9091e524b/href">https://medium.com/media/66ff2dd00de11913ab6e6cc9091e524b/href</a></iframe><ol><li>Remember, we used here a document-based database called `tinydb` where we create a database and the weather table</li><li>In the callback function (the function that gets called when the consumer pop work from the queue,</li><li>The consumer will keep running and waiting for new work in the queue</li></ol><p><strong>Auth app</strong></p><p>The other part is the web auth. For authentication, we used JWT which the server creates the token and returns it back in the response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba6569af27c703e761366192b2fcc661/href">https://medium.com/media/ba6569af27c703e761366192b2fcc661/href</a></iframe><p>In the code above we created post /login endpoint, it authorizes the name and password then creates a token and sends it back in the response.</p><h3>Scale it up</h3><p>The question now, how to scale this design in case we need to. To answer this question we need first to identify the bottleneck of the system. Is it the client, the WebSocket app, the Auth or the datastore. In case we got 1M clients all of them are sending messages to the server.. you guessed it .. its the WebSocket app.</p><p>To scale up the server we can simply replicate the server, and the auth app will return the queue id with the socket information so the client would know which socket server to connect with. Here is the updated architecture design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISzRJQBT3Am6oqub.png" /><figcaption>Scale up the socket servers</figcaption></figure><h3>Run the app</h3><p>If you want to run the app you can pull it from <a href="https://github.com/mohanadkaleia/rwis">here</a></p><p>Run the client on the station:</p><p>python station.py</p><p>Run the auth app:</p><p>python app.py</p><p>Run the WebSocket server:</p><p>python server.py</p><p>Note: Rabbitmq server should be running as well.</p><h3>Conclusion</h3><p>To wrap up, in this post we illustrated an architecture design for an IoT system that scales up.</p><p>As a reminder, the code we demonstrated here is not suitable for production. It was just a demo to explain the idea. The Github repo that contains the code is here: <a href="https://github.com/mohanadkaleia/rwis">https://github.com/mohanadkaleia/rwis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*FzkwDKgNAUeUm9Fd.gif" /></figure><p>Will be happy to hear your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b7eac71935" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tabu Search — gentle introduction]]></title>
            <link>https://medium.com/@m.kaleia/tabu-search-gentle-introduction-46c479eb6525?source=rss-8dad05a7387b------2</link>
            <guid isPermaLink="false">https://medium.com/p/46c479eb6525</guid>
            <category><![CDATA[tabu-search]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[travelling-salesman]]></category>
            <dc:creator><![CDATA[Mohanad Kaleia]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 19:11:14 GMT</pubDate>
            <atom:updated>2018-10-28T19:11:14.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tabu Search — gentle introduction</h3><p>Recently, I attended a course on discrete optimization on Corsera. One of the problems I was trying to solve is the Travelling Salesman Problem, the famous NP-Hard optimization problem. The course explained how to solve several real problems with several algorithms, one of them is <a href="https://en.wikipedia.org/wiki/Tabu_search">Tabu Search</a>.</p><p>Today, in this post I will explain this algorithm and implement it using Python to solve the Travelling Salesman Problem TSP.</p><h3>Hmm.. so what is Tabu search and where can I use it?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6Yg4GUVgIUg3bf7W%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6Yg4GUVgIUg3bf7W%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o6Yg4GUVgIUg3bf7W%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="185" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3423360ff3b77833af2a82cc41c71b3/href">https://medium.com/media/d3423360ff3b77833af2a82cc41c71b3/href</a></iframe><p>Tabu Search is a meta heuristic procedure for solving optimization problem designed to guide other methods to escape the trap of local minima. Tabu Search is used to find optimal and nearly optimal solutions for a wide range of classical and practical problems. From scheduling, to telecommunications, character recognition to neural networks. To avoid falling in a local minima, it uses a memory so it can remember moves and solutions that are already exploited. Also, it uses memory functions to allow searching strategies like intensify and diversify (will explain them soon).</p><p>Tabu Search can be used to guide other processes that uses a set of moves for transforming one solution into other and provides a guidance for measuring the attractiveness of theses moves. Example of moves are swapping between two tasks, changing value of a variable (increase, decrease).</p><p>A partial list of Tabu Search applications:</p><ol><li>Employee scheduling</li><li>Maximum Satisfiability problems</li><li>Character recognition</li><li>Space planning and architectural design</li><li>Telecommunication path assignment</li><li>Probabilistic logic problem</li><li>Neural network pattern recognition</li><li>Machine scheduling</li><li>Traveling salesman problem</li><li>Graph coloring</li></ol><h3>Tabu Search Principles</h3><p>Tabu Search based on three main concepts:</p><ol><li>The use of flexible attribute based memory structures, that allows evaluation criteria and historical search information to be exploited move thoroughly than by rigid memory structures or by memory-less systems.</li><li>A mechanism that evaluate the movement based on a specific criteria in tabu search</li><li>The use of memory functions of different time spans from short term to long term, to implement strategies for intensify — to focus on a specific region, to diversifications — that drive the search in new regions.</li></ol><h3>Short term memory and aggressive search:</h3><p>Short term memory in tabu search can be represented as an aggressive exploitation that seeks to make the base move possible. By making a list of candidate moves that can lead to a new solution from the current solution.</p><p>Tabu Search provides constrains that prevents repeating of certain moves. By considering those moves as forbidden (Tabu)… (Ahhh that’s why it called Tabu Search!). Tabu Search is intended to prevent cycling back into a local minima, and broadly to introduce the search to follow a new trajectory.</p><p>But.. how can Tabu determine the best candidate? Simple!, using the objective function!..</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0HlFh5OUTG9d3Lb2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0HlFh5OUTG9d3Lb2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0HlFh5OUTG9d3Lb2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="335" frameborder="0" scrolling="no"><a href="https://medium.com/media/d714554662db8817be1c546412f841ec/href">https://medium.com/media/d714554662db8817be1c546412f841ec/href</a></iframe><p>Things are still not clear?! don’t worry I did not understand it also before I saw the following boxed graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT8VcBlgiWkS5qAQjm-Y0Q.png" /><figcaption>Tabu-search short term memory component — taken from [1]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXfnLMJUc9GJq9bortXBYQ.png" /><figcaption>Selecting the best admissible candidate — taken from [1]</figcaption></figure><h3>Example time!!!</h3><p>ِA simple illustration for Tabu Search is the minimum cost spanning tree problem that includes constraints to prevent certain edge from appearing . The problem can be represented by five nodes so the spanning tree consists of four edges and every edge has a cost as illustrated in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxxVx_W-MB08p7CbMq5rMA.png" /><figcaption>Spanning Tree Problem</figcaption></figure><p>In this problem we need to minimize the cost of connecting the nodes with each other. Every edge is represented here by xi where i=[0..7] and xi can take 0 or 1 (0 the edge does not exists). Every edge has a cost. For example the cost of the initial solution here is 6+2+8+0 = 16 (pretty good huh).</p><p>But wait.. don’t forget the other part of the problem, some edges are prohibited to appear.. so lets put some constraints here:</p><blockquote>x1 + x2 + x6 ≤ 1</blockquote><blockquote>x1 ≤ x3</blockquote><p>When we violate those constraints we penalize the cost of 50 for each unit of violation . So in the figure above we have 2 violations so the penalty is 100. and the total cost of that spanning tree is <strong>116</strong> :)</p><p>We need to find a solution that gives a low cost without violating the constrains above. To apply Tabu Search we apply swap transform by dropping one edge and add another to transform to another solution.</p><p>When we choose to add an edge we must drop another edge in a way that don’t create a cycle. Admissible move is the move that have the lowest cost taking into consideration the violation penalty cost.</p><p>Tabu restriction is defined here as the added edge we define as a tabu status. This makes edges that are selected as tabu to not been dropped out of the tree as long as they are tabu. In the example we allow only two edges to be tabu. Which means any added edge remains tabu for two iteration.</p><p>The aspiration criteria here is to override a tabu status if the resulting tree is better than the best tree produced so far. We will run the algorithm now for and discuss each iteration. Iterations are represented in figure 1 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oM9xQ4-MyyxrMsv3qEOUjA.png" /></figure><p><strong>Iteration1</strong>: from iteration 1 the best move that we can do in a way not to violate the constrains is by adding x3 and dropping x1. This will reduce the penalty from 100 -&gt; 0. while increasing the cost from 16 -&gt; 28. X3 now is considered as tabu.</p><p><strong>Iteration 2</strong>: now by the tabu status rule we make x3 as tabu. so we can’t drop x3. From the remaining the best choice is to add x7 and drop x6. Then make x7 as tabu. The chosen move produce worst cost than the previous.</p><p>Now we have x3, x7 are considered as Tabu. and if we want to make any move we will make the cost worse. so we are in a state that has a bad cost and we can’t make any other move which is called local minimum.</p><p><strong>Iteration 3</strong>: Now since we reach a local minimum we can override tabu status by adding x2 and drop x3. This move satisfy the aspiration criterion by producing a tree that has a better cost so we make this move.</p><p><strong>Iteration 4</strong>: X2, X7 are now tabu. The algorithm will continue the moves by adding x3 and dropping X5. X3 and X2 now are tabu</p><p><strong>Implementation:</strong></p><p>I forked an implementation of tabu search in Python and improved it to solve the problem of Traveling Salesman, please feel free to use and modify the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e559c582cc3527baac2e59cde4e8e2a4/href">https://medium.com/media/e559c582cc3527baac2e59cde4e8e2a4/href</a></iframe><p><strong>Conclusion:</strong></p><p>Tabu search is a meta heuristic search algorithm that utilize the idea of having short term memory to avoid sticking in a local minima. It has been used in many applications one of them is Traveling Salesman Problem. Speaking about TSP it worth to mention that the best reported algorithm to solve it is guided local search algorithm.</p><p><strong>References:</strong></p><p>I used the following reference as the main source of information written in this post (really this is the best resource for tabu search:</p><ol><li><a href="https://www.researchgate.net/publication/242527226_Tabu_Search_A_Tutorial">https://www.researchgate.net/publication/242527226_Tabu_Search_A_Tutorial</a></li><li><a href="https://en.wikipedia.org/wiki/Tabu_search">https://en.wikipedia.org/wiki/Tabu_search</a></li><li><a href="http://www.cleveralgorithms.com/nature-inspired/stochastic/tabu_search.html">http://www.cleveralgorithms.com/nature-inspired/stochastic/tabu_search.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46c479eb6525" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>