Friday, June 9, 2017

Data architectures in Cloud Computing. 
Traditional data processing architecture has changed a lot from where they used to be part of the ubiquitous three tier architecture involving databases, to being more distributed, scaled up and scaled out, sharded and hosted on private and public clouds, maintained on clusters and containers with shared volumes, hosted in memory and even becoming hybrid to involve SQL and NoSQL technologies. We describe some of these evolutions in this article. 
There are some trends with data that are undeniably and renowned as motivating this evolution. First, data sets are sticky. They are costly to acquire, transfer and use in a new location. This also meant that innovation will be increasingly accomplished by end users rather than an expert provider. Consequently the ecosystem has been changing. Second, data is growing rapidly. The order of scale has increased from GigaBytes to TeraBytes to PetaBytes and so on. The data is increasingly being gathered from numerous sensors, logs and networks.  More commonly, database administrators find that their mysql database starts becoming slower and slower even with master slave replication, adding more RAM, shardingdenormalization and other SQL tuning techniques. 
Therefore architects often choose to spread out their options as data grows and is still manageable and portable at that stage. They get rid of joins and denormalize beforehand, they switch to data stores that can scale such as MongoDB and have applications and services take more compute than storage. As data grows, scalability concerns grow. This is where Big Data comes in. Initially much of the growth in data was exclusively for analytics purposes so Big Data became synonymous with MapReduce kind of computing. However that begins to change when there are more usages of the data. For example, SQL statements are used to work with the data and SQL connectors are used to bridge relational and NoSQL stores. NoSQL is usually supported on a distributed file system with key-values as columns in a column family. The charm of using such system is that it can scale horizontally with the addition of commodity hardware but it does not support the guarantees that a relational store comes with. This calls for a mixed model in many cases. 
Usages have also driven other expressions of the databases. For example, distributed databases in the form of matrix were adopted to grow to large data sets and high volume computations. Separation of data into tables, blobs and queues enabled it to be hosted in much smaller granularity on public and private clouds. When the data could not be broken down such as with Master Data catalogs of a retail store, it was served with its own stack of web services in a tiered architecture that decoupled the dependency on the original large volume data store. Adoption of clusters in various forms other than for Big Data and file systems such as abstraction of Operation System resources enabled smaller databases to be migrated to clusters from dedicated servers.  
 #codingexercise
        static List<String> GenerateEmailAliases(String firstname, String lastname) 
        { 
            var ret = new List<String>();
             ret.Add(firstname);
             ret.Add(lastname); 
            for(int i = 0; i < firstname.Lengthi++) 
                for (int j = 0; j < lastname.Lengthj++) 
                { 
                    var alias = firstname.Substring(0, i + 1) + lastname.Substring(0, j + 1); 
                    ret.Add(alias); 
                } 
            return ret; 
        }

bool IsPowerOfTwo(uint x)
{
return (( x != 0) && ((x & (x-1)) == 0);
}
// reverse a linkedlist in groups of k
    static Node Reverse(int k, ref Node root)
    {
        Node current = root;
        Node next = null;
        Node prev = null;
        int count = 0;
        while (current != null && count < k)
        {
        next = current.next;
        current.next = prev;
        prev = current;    
        current = next;
        count++;
        }
        if (root != null)
            root.next = Reverse(k, ref next);
        return prev;

    }


Thursday, June 8, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Then we added  serverless computing to the mix. Today we discuss marathon in detail. This is another specialization that is changing the typical landscape of application-database deployments in the traditional OLTP store.
Marathon is a container orchestration platform for Mesosphere's Datacenter Operating System (DC/OS) and Apache Mesos. Mesosphere is a platform for building data rich applications that can be portable across hybrid cloud. Mesos is a distributed systems kernel that unshackles us from a single box while providing us the same abstractions for CPU, Memory, Storage and other compute resources. It enables us with a fault-tolerant and elastic distributed systems. Together Marathon and Mesos provide a one-stop shop for an always-on always-connected, highly available, load-balanced, resource managed and cloud-portable deployment environment that is production ready.  Contrast this with the traditional dedicated resources in deployment environments in many enterprises and we see how managed the deployment environment has become. Moreover, it enables service discovery and load balancing so applications and services can be written as many as needed and configured with load balancer.  Anything that is hosted on Marathon automatically comes with health checks. Not only this we can also subscribe to events and collect metrics. The entire marathon framework is available via REST API for programmability. 
Perhaps the most interesting application is the hosting of database service on the Marathon containers. While load balancing for user services is a commonly understood practice, the same for a database service is lesser known. Marathon, however treats all services as code that can run on any container hosted on the same underlying distributed layer. The data persists on a shared volume and intra-cluster connectivity to the shared volume is trivial latency and redirection. That said storage and networking efficiency still needs to be carefully studied. Also, persistent volumes are used for applications to preserve they state because when they are restarted, they lose their state. A local volume that is pinned to the node will be available when that node relaunches. This bundles up the disk and the compute for that node.

#codingexercise
Find the first non-repeating character in a string
char GetNonRepeating(string str)
{
var h = new Hashtable();
for (int i = 0; i < str.Length; i++)
       if (h.Contains(str[i]))
           h[str[i]] += 1;
       else
           h.Add(str[i], 1);
char c= '\0';
for (int i = 0; i < str.Length; i++)
       if (h[str[i]] == 1) {
             c = str[i];
             break;
       }
return c;
}

Wednesday, June 7, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Then we added  serverless computing to the mix. Today we continue the discussion.
Applications have evolved with cloud computing. What used to be monolithic and deployed on mere separation between Application dedicated virtual machines and database dedicated storage, was made more modular and separate into deep vertical partitions with their own operating systems. With twelve factor applications, it was easier to take advantage of containers. This worked well with platform as a service and docker containers. It is possible however to go further towards decomposing the application modules into compute and data access intensive functions that can be offloaded into its own containers with both function as a service and backend as a service.  The ease of modifications is very appealing when we look at individual functions packaged in a container by itself.  Both public clouds currently support this form of computing. AWS Lambda and Azure Functions can be executed in response to events at any scale.
There are a few tradeoffs in the serverless computing that may be taken into perspective. First, we introduce latency in the system because the functions don't execute local to the application and require setup and teardown routines during invocations.Moreoever, debugging of serverless computing functions is harder to perform because the functions are responding to more than one applications and the callstack is not available or may have to be put together by looking at different compute resources. The same goes for monitoring as well because we now rely on separate systems. We can contrast this with applications that are hosted with load balancer services to improve availability. The services registered for load balancing is the same code on every partition. The callstack is coherent even if it is on different servers. Moreover, these share the same persistence even if the entire database server is also hosted on say Marathon with the storage on a shared volume. The ability of Marathon to bring up instances as appropriate along with the health checks improves the availability of the application. The choice of using platform as a service or a marathon cluster based deployment or serverless computing depends on the application.
  #codingexercise
Given a preorder traversal of a BST, find the inorder traversal
List<int> GetInOrderFromPreOrder(List<int> A)
{
if (A == null) return A;
return A.sort();
}
int power(uint base, uint exp)
{
int result = 1;
if (exp == 0) return result;
for (int i = 0; i < exp; i++)
      result = result * base;
return result;
}
int power(unit base, uint exp)
{
int result = 1;
while (exp> 0)
{
 if (exp & 1)
      result = result * base;
 base = base * base;
 exp == exp >> 1; 
}
return result;
}

Tuesday, June 6, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Then we added  serverless computing to the mix. Today we continue the discussion. This time we focus on Docker support.
OpenWhisk supports Docker actions. This means we can execute binaries on demand without provisioning virtual machines. Docker actions are best suited where it is difficult to refactor an application into smaller set of functions. This is a common use case for existing applications and services. 
When we request images from Docker for executing the action, these take longer because the latency is high. It depends on the size of the image and the network bandwidth. Contrast this with the pool of warm containers that don't require a cold start.  Moreover, Docker images may not be posted on a public hub because the code to execute on them may be proprietary and it will violate security. These were mitigated with OpenWhisk providing a base image for Docker actions. Also, a Docker action can now receive a zip file with an executable.
The suggestion here is that we dont need to create custom images. This saves time on latency. A base image is already provided. Also, the executable can be switched. Without customizing images and not sharing them, we don't compromise on security. In addition, since only the executables are switched, the time it takes to execute the code is less.

#codingexercise
A bot is an id that visits the site m times in the last n seconds. Given a list of entries in the log sorted by time, return all the bots id.
Yesterday we solved this with iteration over the relevant window of the log. This is a typical question on logs and events both of which are stored in Time Series Database.
Time series database helps with specialized queries for the data. Unlike a relational data that serves an OLTP system, the time series is a continuous stream of events and often at a high rate.
In the logs, Bots generally identify themselves with their user agent string and they obey the rules in the robots.txt file of the site. Consequently, we can differentiate the bots from the logs into those that behave and those who don't. And the ones that do leave an identification string.
      count = 0;
      string pat = @"(?<bot_name>Google?)bot\W";
      Regex r = new Regex(pat, RegexOptions.IgnoreCase);
      foreach (var kvp in h)
      {
           Match m = r.Match(h[kvp.key]);
           if (m.Success)
               count++;
      }
one more:
count the number of ways elements add upto N using array elements with repetitions allowed:
int GetCount(List<int> A, int sum)
{
var counts = new int[A.Count + 1] {0};
for ( int i = 0; i < A.Count; i++)
    counts[i] = 0;
counts[0] = 1;
for (int i = 1; i <= sum; i++)
    for (int j = 0; j < A.Count; j++)
        if (i >= A[j])
              counts[i] += counts[i-A[j]];
return counts[sum];
}
Alternatively, this can be done with backtracking instead of dynamic programming as we showed with the help of the Combine method involving repetitions in the earlier posts.

Monday, June 5, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Then we added  serverless computing to the mix. Today we continue the discussion.
Serverless computing is open by design.  The engine and the event emitter/consumer is open. The interface is open. Its components are Docker, Kafka, Consul which are all open The tools used with this are also open.  
Since the emphasis is on actions, triggers, rules and the deployment and runtime are managed, it is easiest to upload and use it. Actions are the event handlers. They can run on any platform. Typically they are hosted in a container. They can be changed to create sequences and to increase flexibility and foster reuse. An association of a trigger and an action is called a rule. Rules can be specified at the time the actions are registered. A package is a collection of actions and triggers. It allows you to outsource load and calculation intensive tasks. This allows share and reuse. The only drawback is that troubleshooting is more tedious now as there is more correlation to be done. However, actions can be both synchronous and asynchronous and expressed in their own language and runtime. This means we can get responses in blocking and non-blocking manner.  The runtimes are found in the container hosted. 
In the standalone mode, the containers are made available with VirtualBox. In the distributed environment, it can come from PaaS.  These actions do not require predeclared association with containers which means the and the infrastructure does not need to know what the container names are. The execution of the action is taken care of by this layer.

#codingexercise
A bot is an id that visits the site m times in the last n seconds. Given a list of entries in the log sorted by time, return all the bots id.
Hashtable<int, int> GetBots(Log[] logs, int m, int n)
{
var h = new Hashtable<int, int>();
var min = Math.min(logs[logs.Length-1]-n, 0);
for (int i = logs.Length - 1; i >= min; i--)
     if h.Contains(logs[i].id)
        h[logs[i].id] += 1;
     else
        h.Add(logs[i].id, 1);
foreach(var kvp in h)
      if (h[kvp.key] < m)
         h.Remove(kvp.key)
return h;
}

Sunday, June 4, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Then we added  serverless computing to the mix. Today we continue the discussion.
The serverless architecture may be standalone or distributed.  In both cases, it remains an event-action platform to execute code in response to events. In the latter case, it can be offered as a managed service on IBM Bluemix. The console to this service gives a preview of all the features on OpenWhisk. We can execute code written as functions in many different languages. The BlueMix takes care of launching the functions in its own container.  Because this execution is asynchronous to the frontend and backend, they need not perform continuous polling which helps them be more scaleable and resilient. OpenWhisk introduces event programming model where the charges are only for what is used. Moreover it scales on a per-request basis. Together these three features of serverless deployment, granular pricing and scaling make OpenWhisk an appealing event driven framework. Even the programming model is improved. Developers only need to focus on Triggers, Rules and Actions.  Invocations can be blocking, non-blocking and periodic, different languages are supported, and it allows parameter binding, chaining and debugging. Both the engine and the interface are open and implemented in scala. In fact, it is better than PaaS because not only the runtime but the deployment is managed too.
All requests pass through an API gateway because it facilitates security, control, mediation, parameter mapping, schema validation and supports different verbs. Routes and actions can both be defined. CLI, UI and API are also available

Internally OpenWhisk uses a database to store actions, parameters and targets.  This database can be standalone or distributed and is usually couchdb or cloudant respectively. 
It uses a Message Bus like to enable interactions between load balancers, activators and invokers. Activators process events produced by triggers. An activator can call all actions bound by a rule to a particular trigger. Invokers perform actions against a pool of containers. Actions are invoked on containers from a pool that are maintained warm.
#codingexercise
Reverse a linked list in O(1) storage
null
1
1-2
1-2-3
void Reverse(ref Node head)
{
Node current = head;
Node prev = null;
while (current)
{
var next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}

Saturday, June 3, 2017

We talked about the overall design of an online shopping store that can scale starting with our post here. Then we proceeded to discussing data infrastructure and data security in a system design case in previous posts. We started looking at a very specialized but increasingly popular analytics framework and Big Data to use with data sources. For example, Spark and Hadoop can be offered as a fully managed cloud offering. we continued looking at some more specialized infrastructure including dedicated private cloud. Today we add serverless computing to the mix.
Serverless computing is about Backend as a service as well as Function as a service. A Backend as a service isone which allows a portion of the backend activities to be expressed as functions that execute elsewhere on container. These can be both synchronous and asynchronous. This allows the backend services to be lighter. It can involve any number of operations  and as granular as appropriate. A Function as a Service allows the fat client and single page applications to be lighter as the don't necessarily have to do all the computations in one page. They can be broken down into functions that evaluate elsewhere. In a model-view-controller architecture, we had multi-page applications but these allow super efficient and rich single page applications.
In the case of the store, the functions may be listed as follows:
1) Authentication function - Most authentication mechanism is universal and consolidated for the application to allow users to sign into membership providers. These can be offloaded to their own functions instead of being performed by the same server that responds to shopping experience.
2) The database access - Much of the data is in the form of relational data that requires the same amount of data translations but they need not be done in the server and can be fine granular .
3) MVC becomes a single page again. As discussed, the front-end allows single page applications to be composed of hundreds of smaller functions when appropriate.
4) Search Function - Some of the methods such as search are orthogonal to the shopping experience but equally important. Therefore they can be offloaded.
5) Purchase Function - This is probably the most used function but it is almost independent of the user or the products since it involves card activity. Consequently it is a separate function in intself.
Not just functions but messages can also be translated. Functions can be queued with Kafka.
Thus functions instead of modules become an appealing design.
#codingexercise
int IndexOfUnusedInUnordered(unordered, item, ref h, ref used)
{
assert(h.Contains(item));
int index = unordered.IndexOf(item 0);
while (index != -1 && used[index] != true && index < unordered.Count)
{
if (used[index] != true){
    used[index] = true;
    h[item] -= 1;
    break;
 }
index = unordered.IndexOf(item, index+1);
}
return index;
}