




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































47 ................................................................................................................................................................................ 211 48 ................................................................................................................................................................................ 211 49 ................................................................................................................................................................................ 212
As data volumes and user demands grow, scalability is required:
- Vertical scaling (scale up): adding more power/resources (CPU, RAM) to a single node (high-performing- servers). Downside: supercomputers become disproportionately expensive; cost of super-computers is not linear with respect to their resources. - Horizontal scaling (scale out): adding more low-cost nodes (commodity servers) to a system. Costs grow almost linearly with respect to the number of added nodes. Data center efficiency is a difficult problem to solve. For data-intensive workloads, a large number of commodity servers is preferred over a small number of high- performing servers. At the same cost, we can deploy a system that processes data more efficiently and is more fault tolerant. Horizontal scalability (scale out) is preferred for big data applications. However, it introduces the complexity of distributed computing → New systems hiding the complexity of the distributed part of the problem to developers are needed Key challenges in cluster computing include: - Distributed programming: dividing problems, parallelizing tasks, synchronizing processes, and scheduling distributed applications to maximize performance and reduce failures. - Distributed storage: ensuring persistence even if nodes fail. Redundancy helps but adds complexity. - Network bottlenecks: mitigated by reducing data transfers and bringing computation closer to data. Distributed computing is not new: since the 1960s there was High-Performance Computing, in the 1990s Grid Computing and distributed databases. However, Big Data volumes demand newer and more advanced solutions, as traditional techniques are no longer sufficient.
A Big Data architecture is designed to handle ingestion, processing, and analysis of data that is too large or complex for traditional database systems. It usually covers multiple workloads:
- Batch processing of large “at rest” datasets, - Real-time processing of streaming data “in motion,” - Interactive data analysis, - Predictive analytics & Machine Learning to extract models and patterns. This architecture is useful when: - datasets are too large for traditional databases, - unstructured data must be transformed into useful information, - continuous data streams must be captured and analysed in real time or with low latency. The most widely used architecture is the Lambda Architecture , proposed by Nathan Marz in 2011. Before this, scalable systems like Hadoop (for large-scale batch processing) and NoSQL databases (e.g., Cassandra, Riak) emerged. Each solved specific problems but had trade-offs: - Hadoop: excellent for batch parallel processing, but high latency → unsuitable for real-time needs. - NoSQL databases: scalable but less flexible than SQL; mutable, hence more error prone. Individually, these tools are not universal solutions. But when integrated intelligently, they form scalable, fault-tolerant systems while keeping complexity manageable. This is the core idea behind the Lambda Architecture , which combines their strengths to provide a balanced and complete view of data.
The Lambda Architecture is designed to process massive datasets by combining batch processing and stream processing. It balances three key aspects: latency, throughput, and fault tolerance.
- Batch processing ensures a complete and accurate view of historical data. It stores all the incoming data in its raw form and performs batch processing on the data. The result of this processing is stored as batch views. - Stream processing provides real-time insights from incoming data. This bath is designed for low latency, at the expense of accuracy. It relies on an append-only, immutable data model : new events are added in chronological order without modifying existing data, preserving a single “source of truth.” The architecture is fault-tolerant to both hardware and human errors, supports low-latency queries, fast updates, linear scalability by adding nodes, and extensibility for future functionalities. Queries are treated as functions on the entire dataset. Their key properties are: - Latency : the time it takes to run a query, - Freshness : how up-to-date results are, - Accuracy : often traded off for scalability and performance, sometimes allowing approximations.
Lambda Architecture has two main layers: cold path (batch layer) and hot path (speed layer). All data entering the system is dispatched to both the batch layer and the speed layer for processing. The batch layer has two functions:
- managing the master dataset (an immutable, append-only set of raw data) - Performs batch computations to produce batch views (complete pre-computed results). The serving layer indexes the batch views so that they can be queried in low-latency, ad-hoc way. Merges historical (batch) and recent (real-time) results into unified, up-to-date views. When a query is executed, the final result is obtained by combining batch views (accurate but less fresh) with real-time views (fresh but less precise). The speed layer compensates for the high latency of updates to the serving layer and deals with recent data only. Any incoming query can be answered by merging results from batch views and real-time views. Processes the most recent data in real time or near real time, sacrifices some accuracy for low latency and provides immediate insights using streaming technologies.
To avoid these issues, it’s best to combine small files into larger ones before loading them into HDFS. Other solutions include using Hadoop Archives or container formats like SequenceFiles and Avro. By organizing data this way, Hadoop can manage it efficiently, ensuring better performance and scalability. Client applications interact with HDFS through dedicated APIs. When a client wants to access a file, it first communicates with the master node to discover which chunk servers hold the relevant pieces of data. Once this information is obtained, the client then connects directly to the corresponding chunk servers to read or write the data. Beyond the core Hadoop infrastructure, a variety of related projects and systems have been developed to extend its capabilities and target specific types of problems. Some key examples include:
- Hive : a distributed relational database built on top of MapReduce, which enables users to query data stored in HDFS using a SQL-like language. - HBase : a distributed, column-oriented database that leverages HDFS for persistent storage. - Pig : a high-level data flow language and execution environment, also based on MapReduce, designed for analyzing and processing very large datasets. → it is no longer available - Sqoop : a tool that facilitates efficient transfer of data between traditional relational databases (or flat files) and HDFS. - ZooKeeper : a distributed coordination service that provides essential primitives, such as distributed locks, to manage large-scale, distributed applications. Each of these systems is designed to solve a specific class of problems, making the Hadoop ecosystem both flexible and extensible. RESUME: Hadoop is a framework made to handle very large datasets by splitting them across many computers (a cluster). It’s great for data-intensive workloads, not for heavy calculations — that’s what high-performance computing (HPC) is for.
In Big Data systems, the idea is to scale out, not up. Instead of upgrading existing machines with more CPU power or memory, we increase the number of servers in the cluster. This approach allows for better scalability and cost efficiency. Another key concept is to move processing to the data, not the other way around.
All the phases can be paralyzed. For the map phase, if two pairs of the same word are sent to two different servers, then they are shuffled together with no problem. The Map phase can be viewed as a transformation over each element of a data set
- This transformation is a function m defined by developers - m is invoked one time for each input element - Each invocation of m happens in isolation - The application of m to each element of a data set can be parallelized in a straightforward manner. The Reduce phase can be viewed as an aggregate operation - The aggregate function is a function r defined by developers - r is invoked one time for each distinct key and aggregates all the values associated with it - Also the reduce phase can be performed in parallel and in isolation - Each group of key-value pairs with the same key can be processed in isolation The shuffle and sort phase is always the same i.e., group the output of the map phase by key - It does not need to be defined by developers - It is already provided by the Hadoop system
Key-value pair is the basic data structure in MapReduce. Keys and values can be: integers, float, strings, … They can also be (almost) arbitrary data structures defined by the designer. Both input and output of a MapReduce program are lists of key-value pairs. Note that also the input is a list of key-value pairs. The design of MapReduce involves:
In many applications, the key part of the input data set is ignored i.e., usually the map function does not consider the key of its key-value pair argument e.g., word count problem. This means that in many cases, the original key in the input is not important. The map() function often uses only the value and ignores the key. Suppose the input looks like this: (0, "hello world") (1, "hello hadoop") to count words, we don’t care about the line number (the key). We only use the value (the text). So in this case, the key is ignored. Some specific applications exploit also the keys of the input data e.g., keys can be used to uniquely identify records/objects.
When developing a Hadoop MapReduce application, designers and developers primarily focus on defining the Map and Reduce functions (i.e., the logic of map() and reduce()). They do not need to handle the complexity of distributed execution, such as managing the map, shuffle and sort, or reduce phases. The Hadoop framework takes care of coordinating the entire execution of the MapReduce program. This includes running the map and reduce phases in parallel, executing the shuffle and sort phase, scheduling subtasks, and ensuring synchronization between different parts of the workflow. MapReduce programs are usually written in Java and consist of three main components. Each component is implemented as a Java class, and the program uses instances (objects) of these classes to perform its tasks.
- Driver – coordinates the job and the workflow of the application. It is responsible for configuring the job, submitting the job to the Hadoop cluster and coordinating the workflow of the application. It contains the main() method , which is the entry point of the application and can accept command-line arguments. The Driver runs on the client machine, not on the cluster itself. The Driver class usually extends org.apache.hadoop.conf.Configured and implements the org.apache.hadoop.util.Tool interface. It is possible to write a Driver class without extending Configured or implementing Tool, but in that case, you must manually handle low-level details, such as parsing command-line arguments. The developer is responsible for implementing: - main() method – the entry point of the program, - run() method – which configures and launches the job. The run() method defines all the job settings, including: job name, input format and output format, mapper class (class name, input and output types), reducer class (class name, input and output types, number of reducers ); number of mapper is not said by the user but depend on the number of the input block; instead the number of reducers is said by the user and depends on the numbers of distinct key that you have. Not always to increase the number of reducers is the best solution. - Mapper – implements the map function. It processes each input (key, value) pair from the input file and emits a set of intermediate (key, value) pairs, which are temporarily stored on the local filesystem of the computing node (not HDFS). The map() method is invoked once for each input pair, and the Mapper runs on the cluster nodes. Input data is read as key-value pairs from HDFS. Intermediate results are transient: they stored temporarily on the local filesystem of the node producing or processing them. They are not stored in HDFS, and they exist only during computation. The shuffle and sort phase aggregates intermediate results into (key, [list of values]) pairs (One (key, [list of values]) for each distinct key), preparing them for the Reducer. The Mapper class extends org.apache.hadoop.mapreduce.Mapper, which is a generic class with four type parameters: Mapper Developers implement the map() method, which is automatically called by Hadoop for each input (key, value) pair. Inside map(), you can use standard Java code to process the input. To emit results, use: context.write(key, value); (to connect with the cluster) - Reducer – implements the reduce function. It processes each (key, [list of values]) pair generated after the shuffle and sort phase, produces a set of final key-value pairs, which are stored in HDFS as the output of the MapReduce job. The reduce() method is called once per distinct key, and the Reducer also runs on cluster nodes. The Reducer class extends org.apache.hadoop.mapreduce.Reducer, another generic class with four type parameters: Reducer Developers implement the reduce() method, which is automatically called for each (key, [list of values]) pair resulting from the shuffle and sort of the Mapper outputs. Inside reduce(), you process the values using standard Java code and emit results with context.write(key, value); To process data efficiently, Hadoop executes tasks in parallel: it creates one Mapper task for each input split and a user- specified number of Reducer tasks, where each Reducer is responsible for a subset of keys and processes all associated key-value pairs. Both Mappers and Reducers run on the nodes of the cluster, leveraging the distributed nature of Hadoop to scale processing across many servers.
In Hadoop, the OutputFormat class is used to write the results of a MapReduce job back to HDFS. Any class that extends the abstract class org.apache.hadoop.mapreduce.OutputFormat can be used to define how the output is stored. Hadoop provides several predefined OutputFormat classes for standard file formats.
Common OutputFormat Classes:
The Driver is responsible for configuring the job. It sets up the Mapper and the Reducer, specifies the input and output formats, and defines the number of Reducers to use. public class DriverBigData extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Path inputPath; Path outputDir; int numberOfReducers; int exitCode; // Parse the parameters // Number of instances of the reducer class numberOfReducers = Integer.parseInt(args[ 0 ]); // Folder containing the input data inputPath = new Path(args[ 1 ]); // Output folder outputDir = new Path(args[ 2 ]); Configuration conf = this.getConf(); // Define a new job Job job = Job.getInstance(conf); // Assign a name to the job job.setJobName("Basic MapReduce Project - WordCount example"); // DA MODIFICARE // Set path of the input file/folder (if it is a folder, the job reads all the files in the specified folder) for this job FileInputFormat.addInputPath(job, inputPath); // Set path of the output folder for this job FileOutputFormat.setOutputPath(job, outputDir); //The output is ALWAYS a folder, it cannot be a file because it’s generated one file for each reducer. // Specify the class of the Driver for this job job.setJarByClass(DriverBigData.class); // Set job input format job.setInputFormatClass(TextInputFormat.class);
IntWritable> {// Output value type protected void map( LongWritable key, // Input key type Text value, // Input value type Context context) throws IOException, InterruptedException { // Split each sentence in words. Use whitespace(s) as delimiter // (=a space, a tab, a line break, or a form feed) // The split method returns an array of strings String[] words = value.toString().split("\s+"); // Iterate over the set of words for(String word : words) { String cleanedWord = word.toLowerCase(); // Transform word case context.write(new Text(cleanedWord),new IntWritable( 1 ));//emit the pair (word, 1) } } } In Hadoop, the Context parameter in the map method of a Mapper is an object that provides a connection between the Hadoop framework and the Mapper code. It is a fundamental part of the map and reduce mechanism and has several important functions:
- Communication with the framework: The Context allows the Mapper to communicate with the Hadoop framework — for example, to write key-value pairs to the output using the method context.write(outputKey, outputValue); - Configuration and counters: The Context provides access to the job configuration and to counters that can be used to track statistics or debugging information; - Status monitoring: The Mapper’s status can be updated via context.setStatus(), which enables the framework to monitor the progress and activity of the job; - Data access: The Context provides access to the input data and allows the Mapper to read and manage the (key, value) pairs coming from the input. Here’s a typical usage example: protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(" "); for (String word : words) { context.write(new Text(word), new IntWritable(1)); } } In this example, each word is emitted as a key, and the associated value is 1 (the output value). The Context object is used to emit these results.
The Reducer takes as input a key (the word) and a list of values (the number of occurrences). It sums the values for each key and produces the total count for each word. class ReducerBigData extends Reducer < Text, // Input key type IntWritable, // Input value type Text, // Output key type IntWritable> { // Output value type
@Override protected void reduce( Text key, // Input key type Iterable values, // Input value type Context context) throws IOException, InterruptedException { int occurrences = 0 ; // Iterate over the set of values and sum them for (IntWritable value : values) { occurrences = occurrences + value.get(); } context.write(key, new IntWritable(occurrences)); } } The number of invocations with the reduce method is associated with the number for each distinct key. So, for the first file is invoked 7 time.
In the “Standard” MapReduce applications the (key, value) pairs emitted by the Mappers are sent to the Reducers through the network. Some “ pre-aggregations ” could be performed to limit the amount of network data by using Combiners (also called “mini reducers”). Consider the standard word count problem and suppose the input file is split in two input splits. Hence, two Mappers are instantiated (one for each split). With Combiners the (key, value) pairs emitted by the Mappers are analysed in main-memory (or on the local disk) and aggregated by the Combiners. Each Combiner pre-aggregates the values associated with the pairs emitted by the Mappers of a cluster node. Combiners perform “pre-aggregations” to limit the amount of network data generated by each cluster node.